[英]Rails STI. How do I count the number of votes of type Upvote or Downvote for associated model?
Models are Vote
and Issue
. 模型是
Vote
和Issue
。 Issue has_many :votes
. 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. Vote
具有一个STI列类型,当用户对某个问题进行投票时,该列会以“问题”索引上的隐藏形式填充:Upvote
或:Downvote
。 How do I find the number of votes of either type Upvote
or Downvote
for a given issue? 如何找到给定问题的
Upvote
或Downvote
类型的票数? Right now I'm using a method on the Issue
model like this: 现在,我正在
Issue
模型上使用如下方法:
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: 当我循环浏览Issues索引上的所有问题时,我从视图中传递了issue_id,如下所示:
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.
似乎我已经在实例上进行操作时,似乎不必传递ID。 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. 我知道
@issue.Upvote.count
不起作用。
You have a couple of options: define additional associations (or methods) in the Issue
class, or use scope
in the Vote
class. 您有两个选择:在
Issue
类中定义其他关联(或方法),或在Vote
类中使用scope
。 These examples assume Rails 3, though they can be easily adjusted for Rails 2.3. 这些示例假设使用Rails 3,尽管可以轻松地针对Rails 2.3进行调整。
Additional associations in Issue
: 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
. 在这里,我们添加了一些条件来优化问题的相关投票结果,因此您可以调用
issue.upvotes
和issue.downvotes
。 To get the count of upvotes on an issue is, in this case, issue.upvotes.count
. 在这种情况下,要获得对事件的赞成票数,就是
issue.upvotes.count
。
Scope in Vote
: 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
. 投票中的
up
和down
作用域提供了有关投票关系的方法,因此您可以调用issue.votes.up
和issue.votes.down
。 To get the count of upvotes on an issue is simply issue.votes.up.count
. 要获得对某个问题的支持票数,只需
issue.votes.up.count
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.