我需要一些关于 Rails 中投票系统的建议,该系统每月会识别得票最多的人。我有一个可以工作的系统,但对于 Rails 来说是新手,我确信有更有效的方法可用。以下是我当前设置的简化版本(省略 Controller 代码):
class Charity < ActiveRecord::Base
has_many :votes
end
class Vote < ActiveRecord::Base
belongs_to :charity
end
我的架构如下:
ActiveRecord::Schema.define(:version => 20130310015627) do
create_table "charities", :force => true do |t|
t.string "name"
t.text "description"
t.date "last_win"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "votes", :force => true do |t|
t.integer "charity_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
end
我将使用 'whenever' gem 运行 cron 作业来确定每月获胜者并更新慈善机构表的 'last_win' 列。 以下代码是我质疑我的效率的地方:
vote_counts = Vote.count(:group => "charity_id")
most_votes = vote_counts.values.max
winning_ids = vote_counts.map{|k,v| v == most_votes ? k :nil }.compact
charities = Charity.find(winning_ids)
charities.each {|charity| charity.update_attributes(:last_win => Date.today)}
我确信有很多方法可以做得更好,并且希望得到一些建议。如果您对设置投票表/关联的更好方法有建议,我们也将不胜感激。
提前致谢, 共同引用标准
最佳答案
类似这样的事情:
如果只有一个获胜者,我认为这会起作用
winner_id = Vote.group(:charity_id).order("count(*) desc").pluck(:charity_id).first
Charity.find(winner)id).update_attribute!(:last_win => Date.today)
您可以将其修改为关系:
most_votes = Vote.group(:charity_id).order("count(*) desc").count.first[1]
winners = Vote.group(:charity_id).having("count(*) = ?", most_votes).pluck(:charity_id)
Charity.where(:id => winners).update_all(:last_win => Date.today)
确保数据库中的所有内容都正确索引,
您或许可以进一步简化它,但 SQL 会变得更加复杂。
关于ruby-on-rails - Ruby on Rails - 每月最高票数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15329643/