Reputation: 15471
Lets say I had the following setup
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
And for some reason, I wanted to only allow a given user to have one address of a given color.
How would I lock down? something like
validates :address.house_color.unique
Except functional....
Thanks!
Upvotes: 0
Views: 167
Reputation: 6414
Another way would be to use 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? }
Upvotes: 0
Reputation: 6808
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
Upvotes: 1