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 almost 2 years ago by Rodney Hammad
Posted almost 2 years 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 = self.restaurant_id)
errors.add(:user_id, 'This user has already reviewed this restaurant before') if reviews_of_given_restaurant > 1

Let me know if you're still having trouble!