0

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!

tereško
  • 58,060
  • 25
  • 98
  • 150
Abraham P
  • 15,029
  • 13
  • 58
  • 126

2 Answers2

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
Daniel Evans
  • 6,788
  • 1
  • 31
  • 39
0

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? }
hobberwickey
  • 6,118
  • 4
  • 28
  • 29