简体   繁体   English

Rails - 如何限制用户为每个关联输入多个记录

[英]Rails - how to restrict user from entering more than one record per association

I am new to rails and have not been able to find something for this. 我是rails的新手,但却找不到适合自己的东西。

In my app, I have Products, Reviews, & Users. 在我的应用程序中,我有产品,评论和用户。

Reviews belongs_to users & products while both users and products "has_many" reviews. 评论belongs_to用户和产品,同时用户和产品“has_many”评论。

However, I want to restrict users from entering multiple reviews per product (each product is unique). 但是,我想限制用户为每个产品输入多个评论(每个产品都是唯一的)。 So if a user creates a review for a product and tries to write another review for the same product, they'd be told they are not allowed to but can edit their existing review. 因此,如果用户为产品创建评论并尝试为同一产品撰写另一篇评论,则会告诉他们不允许这样做,但可以编辑他们现有的评论。

My question is: Should I do this at the controller level, or is possible to do it with a validation (which seems like a simpler solution)? 我的问题是:我应该在控制器级别执行此操作,还是可以通过验证(这似乎是一个更简单的解决方案)来执行此操作? Just not sure how to approach it. 只是不知道如何处理它。

You can easily do this with a model validation, and an index would help as well. 您可以使用模型验证轻松完成此操作,索引也可以提供帮助。 Warning though, if you do the unique index without the accompanying ActiveRecord validation your saves will fail silently and cause a usability/debugging headache. 但是请注意,如果您在没有附带ActiveRecord验证的情况下执行唯一索引,则保存将无提示失败并导致可用性/调试问题。

This should do it: 这应该这样做:

class Review < ActiveRecord::Base
  validates :user_id, :uniqueness => { :scope => :product_id,
    :message => "Users may only write one review per product." }
end

If you want to add the index, try this in a migration: 如果要添加索引,请在迁移中尝试:

class AddUniquenessConstraintToReviews < ActiveRecord::Migration
  add_index  :review, [:user_id, :product_id],
    :name => "udx_reviews_on_user_and_product", :unique => true
end

Edit : As a full-time Rails dev I still refer to the ActiveRecord docs for refreshers on the syntax of these things pretty regularly. 编辑 :作为一个全职的Rails开发人员,我仍然会经常参考ActiveRecord文档来修复这些事情的语法。 You should too! 你也应该!

Its better to validate in review model. 更好地在评论模型中进行验证。 The following method can be added to the validations.[Assuming you have associations set properly] 可以将以下方法添加到验证中。[假设您已正确设置关联]

def validate_only_one_review_per_user
  !(@user.products.include? @product)
end

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

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