Sto creando una rete sociale in Rails e ho un modello come questo:due colonne non deve uguali tra loro in Rails
create_table "friendships", :force => true do |t|
t.integer "user1_id"
t.integer "user2_id"
t.boolean "hasaccepted"
t.datetime "created_at"
t.datetime "updated_at"
end
Il problema è che non è possibile aggiungere te stesso come amico, così ho provato questo nel mio modello:
def validate
if :user1_id == :user2_id
record.errors.add "You cannot add yourself as a friend."
return false
end
end
E ho questo nel mio controller:
def addfriend
if params[:id]
@friendship = Friendship.new()
@friendship.user1_id = session[:user]
@friendship.user2_id = params[:id]
respond_to do |format|
if @friendship.save
format.html { redirect_to "/" } # Yes, SO users, I will fix this redirect later and it is not important for now.
format.xml { render :xml => @friendship, :status => :created }
else
format.html { redirect_to "/" }
format.xml { render :xml => @friendship.errors, :status => :unprocessable_entity }
end
end
end
end
(dove session[:user]
è l'uid dell'utente attualmente firmato a utente)
Tuttavia, quando vado a http://localhost:3000/profile/addfriend/2.xml
mentre sto firmato come utente 2
, Rails restituisce me il nuovo Friendship
, invece di un messaggio di errore, e quando prendo un guarda il mio database, lo Friendship
è anche lì (e non dovrebbe). Qualcuno può spiegarmi come risolvere questo problema? Grazie
FYI nella migrazione, si può semplicemente utilizzare t.timestamps invece di t.datetime "created_at" e t.datetime "updated_at". –
@Beerlington: ho appena copiato una parte di db/schema.rb –