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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With