简体   繁体   中英

Rails STI. How do I count the number of votes of type Upvote or Downvote for associated model?

Models are Vote and Issue . Issue has_many :votes . Vote has a STI column type that is filled with either :Upvote or :Downvote by a hidden form on the Issues index when a user votes on an issue. How do I find the number of votes of either type Upvote or Downvote for a given issue? Right now I'm using a method on the Issue model like this:

 def upvotes_count(issue_id)
     Upvote.count(:conditions => "issue_id = #{issue_id}")
 end

def downvotes_count(issue_id)
      Downvote.count(:conditions => "issue_id = #{issue_id}")
end

I pass the issue_id from the view when I cycle through all the issues on the Issues index like this:

issue.upvotes_count(issue.id)

Is this right or is there a better way? Doesn't seem like I should have to pass the id when I'm already operating on an instance. I've played around in the console trying to figure it out but can't figure it out. I know @issue.Upvote.count doesn't work.

You have a couple of options: define additional associations (or methods) in the Issue class, or use scope in the Vote class. These examples assume Rails 3, though they can be easily adjusted for Rails 2.3.

  1. Additional associations in Issue :

     class Issue < ActiveRecord::Base has_many :votes has_many :upvotes, :class_name => "Vote", :conditions => ['type = ?', 'Upvote'] has_many :downvotes, :class_name => "Vote", :conditions => ['type = ?', 'Downvote'] end 

    Here, we add conditions to refine the results of associated votes on an issue so you can call issue.upvotes and issue.downvotes . To get the count of upvotes on an issue is, in this case, issue.upvotes.count .

  2. Scope in Vote :

     class Vote scope :up, where(:type => 'Upvote') scope :down, where(:type => 'Downvote') end 

    The up and down scopes in Vote provide methods on vote relations so you can call issue.votes.up and issue.votes.down . To get the count of upvotes on an issue is simply issue.votes.up.count .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM