如何在嵌套属性上强制列的唯一性:

时间:2013-01-10 18:25:35

标签: ruby-on-rails validation unique-constraint rails-activerecord

让我说我有以下设置

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

除了功能......

谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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? }