我在示例Rails应用程序中设计了一个简单的投票系统。
我有一个从Vote模型调用该方法的控制器
@popular_links = Link.includes(:votes).top
这就是top
我的link.rb
工作方式:
def self.top
self.all.sort do |a, b|
# Calculate each link's vote counts
a_votes = a.votes.where(:up => true).count -
a.votes.where(:up => false).count
b_votes = b.votes.where(:up => true).count -
b.votes.where(:up => false).count
# Compare it from highest value to lowest value
b_votes <=> a_votes
end.first(6)
end
我不确定我所做的工作是否有效。
还是有一个单行的Rails SQL命令可以帮助我像这样对计算进行排序?
:up
为:vote
(我的偏好)代码
@popular_links = Link.includes(:votes).top
def self.top
self.all.sort do |a, b|
a_votes = a.votes.sum(:up)
b_votes = b.votes.sum(:up)
b_votes <=> a_votes
end.first(6)
end
- or -
def self.top
self.joins(:votes).select("links.*, SUM(votes.up) as votes_num").order("votes_num DESC").limit(6)
end
我在这里找到了第二个:Ruby on Rails,找到了按购买顺序排序的前5位用户
在db级别,您的boolean
列仅tinyint
在MYSQL中(请在此处检查数据类型),这意味着true
/false
将为1
或0
。因此,该列的总和将给出该链接的净票数
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句