has_many 关联中 x 个对象中的唯一记录

Unique record among x number of objects in a has_many association

我有以下型号

class Acceptance < ActiveRecord::Base
  belongs_to :user
  belongs_to :requested_favor
  belongs_to :offered_favor
end

class RequestedFavor < Favor 
  has_many :acceptances, foreign_key: 'favor_id'
end

class OfferedFavor < Favor
  has_many :acceptances, foreign_key: 'favor_id'
end

多个用户可以向特定的 favor 对象发送 acceptance 请求。 acceptance 有一个布尔值 accepted 属性。

我需要的是当acceptanceaccepted设置为true时,其他acceptance对象不能设置为true。我猜是某种验证或唯一性。我尽力把情况解释清楚了:)

如何实现?非常感谢您的宝贵时间!

解决此问题的最基本方法是在保存接受之前进行检查,并确保它所属的 "OfferedFavor" 实例还没有任何其他 "accepted" 接受。在您的验收模型中,支票看起来像这样:

offered_favor.acceptances.where(accepted: true).count > 0

希望对您有所帮助!