【问题标题】:How to enforce uniqueness of column on nested attributes:如何在嵌套属性上强制列的唯一性:
【发布时间】:2013-01-10 18:25:35
【问题描述】:
假设我有以下设置
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
功能除外....
谢谢!
【问题讨论】:
标签:
ruby-on-rails
validation
unique-constraint
rails-activerecord
【解决方案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
【解决方案2】:
另一种方法是使用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? }