I have vote and votedown tables for posts. I can validate uniqueness within the vote and votedown models to ensure that users cant vote or votedown more than once. I’d like to validate uniqueness across the both models so that a user cant votedown a post that theyve already voted up or vice versa. Ive tried the custom validation, userfaved, defined below but its not working.
class Vote < ActiveRecord::Base
validates_uniqueness_of :user_id, :scope => :article_id #allows only one vote
validate :userfaved
def userfaved
if Votedown.where( :user_id => :user_id, :artcle_id => :article_id).any?
errors.add(:user_id, 'already voted on this')
end
end
class Votedown < ActiveRecord::Base
validates_uniqueness_of :user_id, :scope => :article_id #allows only one votedown
validate :userfaved
def userfaved
if Vote.where(:user_id=> :user_id, :article_id => :article_id).any?
errors.add(:user_id, 'already voted on this')
end
end
It looks like there’s a bug in your validation: the values in the hash you’re passing to
whereare symbols. Change it to the following and it should work:But I think there’s a simpler way to do this. Could you just have one table
Votesand add an attribute to it that records whether it’s up or down? That would make your uniqueness check very simple. If you really want separate classes for it, you could use single table inheritance: have avotestable, a superclassVote, and two subclasses,VoteUpandVoteDown.