简体   繁体   English

Rails validates_uniqueness_of:外键的范围

[英]Rails validates_uniqueness_of :scope on foreign key

I have a model "Product" that belongs_to "Store" (which has_many "products"). 我有一个模型“产品”属于“商店”(has_many“产品”)。 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 哈里斯

It looks like that error is coming from SQLite, not Rails. 看起来这个错误来自SQLite,而不是Rails。 Check the constraints at the database level - maybe you added a unique constraint on :name rather than [:name, :store_id]. 检查数据库级别的约束 - 可能您在:name而不是[:name,:store_id]上添加了一个唯一约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM