【问题标题】:Two columns must not equal each other in RailsRails 中的两列不能相等
【发布时间】:2010-02-19 13:24:51
【问题描述】:

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

但是,当我以用户 2 登录时转到 http://localhost:3000/profile/addfriend/2.xml 时,Rails 会返回新的 Friendship,而不是错误消息,当我查看我的数据库时, Friendship 也在那里(它不应该)。有人可以解释一下如何解决这个问题吗?谢谢

【问题讨论】:

  • 在您的迁移中仅供参考,您可以只使用 t.timestamps 而不是 t.datetime "created_at" 和 t.datetime "updated_at"。
  • @Beerlington:我刚刚复制了 db/schema.rb 的一部分

标签: ruby-on-rails validation model equals


【解决方案1】:

试试这样:

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

【讨论】:

  • 对于 rails 3 需要使用 erros[:base] stackoverflow.com/questions/10284286/…
【解决方案2】:
if :user1_id == :user2_id

那总是错误的——你在比较符号。和写if "user1_id" == "user2_id"一样。

你应该写成if user1_id == user2_id来比较列的值。

【讨论】:

    【解决方案3】:

    更多乐趣:

      validates :user1_id, exclusion: { in: ->(friendship) { [friendship.user2_id] }, message: "Stop it or you'll go blind." }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 2018-05-12
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      相关资源
      最近更新 更多