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 where
are symbols. Change it to the following and it should work:
Votedown.where( :user_id => self.user_id, :article_id => self.article_id).any?
But I think there's a simpler way to do this. Could you just have one table Votes
and 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 a votes
table, a superclass Vote
, and two subclasses, VoteUp
and VoteDown
.
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