How To Setup Validate Only One Review Per User

How can I validate that the user can only add one review per restaurant?? Some steps on how to go about it will help. Thanks

Posted 4 months ago by Rodney Hammad
Posted 2 months ago by Alex Yang

Fortunately, Rails allows for custom validations, so setting this up is not too bad. In your review.rb model file, you would add something like this (not tested):

...
validate :max_one_review_per_user_per_restaurant
...
def max_one_review_per_user_per_restaurant
reviewer = self.user
reviews_of_given_restaurant = reviewer.reviews.where(restaurant_id: self.restaurant_id)
errors.add(:user_id, 'This user has already reviewed this restaurant before') if reviews_of_given_restaurant > 1
end

Let me know if you're still having trouble!

1