我正在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
,而不是错误消息,当我拍摄时看看我的数据库,Friendship
也在那里(它不应该)。有人可以解释一下如何解决这个问题吗?感谢
答案 0 :(得分:13)
试试这样:
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
答案 1 :(得分:4)
if :user1_id == :user2_id
这总是假的 - 你在比较这些符号。这与撰写if "user1_id" == "user2_id"
相同。
您应该将其写为if user1_id == user2_id
以比较列的值。
答案 2 :(得分:0)
更多乐趣:
validates :user1_id, exclusion: { in: ->(friendship) { [friendship.user2_id] }, message: "Stop it or you'll go blind." }