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 

除了功能....

謝謝!

回答

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 
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? } 
使用