【发布时间】:2014-06-09 11:57:46
【问题描述】:
我的项目中有模型用户和产品。用户有一些产品。我希望用户产品仅针对该用户具有唯一的标题。
例如 user1 有一个名为“product”的产品。在这种情况下,user2 也可以拥有一个名为“product”的产品。第一个“产品”不同于第二个“产品”。在表中,两种产品具有相同的名称。但用户可能不会同时拥有这两种产品。
那是我的 Product.rb:
validates :title, :description, presence: true
validate :uniq_of_product_title
def uniq_of_product_title
if Product.where(user_id: user_id).find_by_title(title)
errors.add(:title, "Product already exists")
end
end
所以它起作用了。出现问题然后我编辑描述并尝试更新产品。 Validator 在表中找到创建的产品并给出错误。
问题是我怎样才能使验证的最佳方式?
【问题讨论】:
标签: validation associations unique