Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord uniqueness validation prevents update

I'm writing a web app using Rails, part of which includes giving users the ability to leave reviews for things. I wanted to put a validation in the review model to ensure that one user can't leave multiple reviews of the same item, so I wrote this:

class NoDuplicateReviewValidator < ActiveModel::Validator
  def validate(record)
    dup_reviews = Review.where({user_id: record.user,
                                work_id: record.work})
    unless dup_reviews.length < 1
      record.errors[:duplicate] << "No duplicate reviews!"
    end
  end
end

This validator has the desired behavior, i.e. it guarantees that a user can't review a work twice. However, it has the undesired side-effect that a user can't update an already existing review that he/she left. I'm using a really simple

def update
  @review.update(review_params)
  respond_with(@work)
end

in the reviews controller. How can I change either the validator or the update method so that duplicate reviews are prevented but updates are allowed?

I'm very new to Rails and web development, so I'm sure I've done something goofy here. I didn't use one of the built-in unique validators because what is unique is the user/work pair; there can more than one review by the same user of different works, and there can be more than one review of the same work by different users.

like image 599
Daniel Shapero Avatar asked Sep 29 '22 10:09

Daniel Shapero


1 Answers

You can use validates_uniqueness_of on multiple attributes, like this:

validates_uniqueness_of :user_id, :scope => :work_id

Then a user would not be allowed to review a already reviewed work.

like image 129
Sharvy Ahmed Avatar answered Oct 03 '22 11:10

Sharvy Ahmed