Rails validates_uniqueness_of: foreign key scope

I have a Product model that belongs to the Store (which has_many products). I want to check the uniqueness of the product name, but only in every store.

Now I have this:

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

When I run the save on any product, I get:

SQLite3::ConstraintException: column name is not unique

I am sure there is a simple mistake I am making here. Please enlighten me.

Thank,

Harris

+3
source share
1 answer

This error seems to come from SQLite, not Rails. Check the restrictions at the database level - you may have added a unique restriction on: name, not on [: name ,: store_id].

+2
source

Source: https://habr.com/ru/post/1791566/


All Articles