true do |t| t.integer "use-6ren">
gpt4 book ai didi

ruby-on-rails - Rails 中的两列不能彼此相等

转载 作者:行者123 更新时间:2023-12-04 07:39:34 26 4
gpt4 key购买 nike

我正在 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

问题是你不能将自己添加为 friend ,所以我在我的模型中尝试了这个:
def validate
if :user1_id == :user2_id
record.errors.add "You cannot add yourself as a friend."
return false
end
end

我的 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

(其中 session[:user] 是当前登录用户的 uid)

然而,当我去 http://localhost:3000/profile/addfriend/2.xml当我以用户身份登录时 2 , Rails 还给我新的 Friendship ,而不是错误消息,当我查看我的数据库时, 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

关于ruby-on-rails - Rails 中的两列不能彼此相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2296530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com