Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 225
Zephyr4434 Avatar asked Dec 27 '22 02:12

Zephyr4434


1 Answers

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!

like image 195
Daniel J. Pritchett Avatar answered Apr 08 '23 10:04

Daniel J. Pritchett