0

可以说我有以下设置

class User < ActiveRecord::Base
    has_many :address
    accepts_nested_attributes_for :address, allow_destroy: true
end

class Address < ActiveRecord::Base
    attr_accessible :house_color, :street_address
end

出于某种原因,我只想允许给定用户拥有一个给定颜色的地址。

我要如何锁定?就像是

   validates :address.house_color.unique

除了功能......

谢谢!

4

2 回答 2

1
class User < ActiveRecord::Base
  has_many :address
  accepts_nested_attributes_for :address, allow_destroy: true
  validates_associated :addresses
end

class Address < ActiveRecord::Base
  belongs_to :user
  attr_accessible :house_color, street_address
  validates_uniqueness_of :house_color. :scope => :user_id
end
于 2013-01-10T18:29:13.733 回答
0

另一种方法是使用reject_if

accepts_nested_attributes_for :address, allow_destroy: true, reject_if: proc { |attributes| Address.where(:house_color => attributes["house_color"], :user_id => attributes["users_id]).exists? }
于 2015-02-27T15:42:02.353 回答