Rails validates_uniqueness_of :scope on foreign key

2.7k views Asked by At

I have a model "Product" that belongs_to "Store" (which has_many "products"). I want to validate the uniqueness of the product name but only within each store.

Right now I have this:

class Product < ActiveRecord::Base
  belongs_to :store
  validates_uniqueness_of :name, :scope => :store_id
end

When I run a save on any product now I get:

SQLite3::ConstraintException: column name is not unique

I'm sure there is a simple error I'm making here. Please educate me.

Thanks,

Harris

1

There are 1 answers

1
Brian Deterling On BEST ANSWER

It looks like that error is coming from SQLite, not Rails. Check the constraints at the database level - maybe you added a unique constraint on :name rather than [:name, :store_id].