hcarreras
hcarreras

Reputation: 4612

Validate presence in this belongs_to

I have products and brands products model:

class Product < ActiveRecord::Base
  attr_accessible :brand_id, :title
  belongs_to :brand

  validates :title, :presence => true
  validates :brand, :presence => {:message => 'The brand no exists'}
end

and the brands model

class Brand < ActiveRecord::Base
  attr_accessible  :name
  validates :name, :presence => true

  has_many :products, :dependent => :destroy
end

I want to validate if exist a product with a name in this brand. I mean I could have 2 products with the same name in different brands but not in the same brand.

Upvotes: 1

Views: 637

Answers (1)

lcoq
lcoq

Reputation: 10726

You could use the uniqueness validation with a scope:

validates :name, :uniqueness => { :scope => :brand_id }

Note that you have to specify :brand_id instead of :brand, because the validation can't be made on the relation.

If you don't know it, I suggest you to read the Active Record Validations and Callbacks guide.

NB: the syntax {:foo => 'bar'} is replaced (since Ruby 1.9.2) with {foo: 'bar'}.

Upvotes: 1

Related Questions