Rails - how to prevent a user from entering more than one entry for each association

I am new to rails and could not find anything for this.

In my application, I have products, reviews, and users.

Reviews belong to users and products, while users and products have "has_many" reviews.

However, I want to restrict user access to several reviews of each product (each product is unique). Therefore, if a user creates a review for a product and tries to write another review for the same product, they will be told that they are not allowed, but they can edit their existing review.

My question is: should I do this at the controller level or can I do this with validation (which seems like a simpler solution)? Just not sure how to approach him.

+4
source share
2 answers

You can easily do this with a model check, and an index will also help. A warning, however, if you make a unique index without an accompanying ActiveRecord check, your saved data will fail and cause headaches with ease of use / debugging.

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 an index, try this in migration:

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

Change As a full-featured Rails-dev, I still relate to ActiveRecord docs for updating the syntax of these things pretty regularly. You must too!

+9
source

It is better to check it in the review model. The following method can be added to checks. [Assuming you have the associations set correctly]

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

Source: https://habr.com/ru/post/1484415/


All Articles