我正在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
问题是您无法将自己添加为朋友,所以我在模型中尝试了此操作:
def validate
if :user1_id == :user2_id
record.errors.add "You cannot add yourself as a friend."
return false
end
end
而且我在控制器中有这个:
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
((session[:user]
是当前登录用户的uid)
但是,当我以用户http://localhost:3000/profile/addfriend/2.xml
身份登录时转到2
时,Rails会向我返回新的Friendship
,而不是一条错误消息,并且当我查看数据库时,[ C0]也在那里(不应该)。有人可以解释一下该如何解决吗?谢谢
尝试这样:
Friendship
class Friendship < ActiveRecord::Base
validate :cannot_add_self
private
def cannot_add_self
errors.add(:user2_id, 'You cannot add yourself as a friend.') if user1_id == user2_id
end
end
这永远都是错误的-您正在比较符号。与写if :user1_id == :user2_id
相同。
您应该将其写为if "user1_id" == "user2_id"
以比较各列的值。
更多乐趣:
if user1_id == user2_id