Reputation: 417
We want to implement a system in our Rails app that allows users to rate posts as True or False. Upon user click of True, that will add one vote to the True count for that post. We want to set this system up so that if a user has already clicked True, but wants to switch to False, they can click False, and that vote will transfer over to the False column count, immediately on the client side.
How should we go about implementing something like this?
we currently have this in micropost.rb
belongs_to :user
belongs_to :target_user, :class_name=>"User", :foreign_key=>"belongs_to_id"
has_many :ratings
def rateable_by_user?(user)
self.ratings.where(:rater_id=>user.id).empty?
end
here is our current rating.rb
class Rating < ActiveRecord::Base
attr_accessible :micropost_id, :owner_id, :rater_id, :rating
belongs_to :micropost
belongs_to :target_user, :class_name=>"User", :foreign_key=>"owner_id"
belongs_to :user, :class_name=>"User", :foreign_key=>"rater_id"
scope :trues, where("rating = ?", "true")
scope :falses, where("rating = ?", "false")
end
Upvotes: 1
Views: 107
Reputation: 13621
I think you have the right idea. Not sure why you have two belongs_to for the user model though (i realize there's two foreign keys, i just don't understand the reason for it). I think really this just comes down to creating a new rating object if the user doesn't have one for that post, setting the correct value based on which they click. If they do have an existing rating, simply swap the rating value.
def switch_value
self.rating = !self.rating
end
If that's not what you're looking for, would you mind describing the particular aspect of the problem you are having trouble with?
Upvotes: 1