Rails模型如何检查两个对象是不相等的

时间:2014-06-10 22:24:17

标签: ruby-on-rails activerecord rspec-rails

我有2个型号,Bid&包。如何在模型中验证这可能永远不会成立?

bid.user == bid.item.user

这样单元测试可以通过

describe "user cannot bid on their own package" do
    @bid.user should_not equal @bid.item.user
end

我正在努力确保用户无法对自己的商品出价。

编辑: 我的模特是

class Bid < ActiveRecord::Base
    belongs_to :user
    belongs_to :package

    validates :user_id, presence: true
    validates :package_id, presence: true  
    validates :amount, presence: true, numericality: { greater_than: 0 }

    .....

end

1 个答案:

答案 0 :(得分:1)

class Bid < ActiveRecord::Base
validate :cannot_bid_on_self

def cannot_bid_on_self
  if user.id == item.user.id
    errors.add(:user, "can't bid on own item")
  end
end
...