简体   繁体   中英

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.

In my app, I have Products, Reviews, & Users.

Reviews belongs_to users & products while both users and products "has_many" reviews.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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