开发者

Rails validates_uniqueness_of :scope on foreign key

开发者 https://www.devze.com 2023-02-10 13:39 出处:网络
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.

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 开发者_如何学Cany 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


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].

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号