我需要一些关于投票系统的建议,这些投票系统可以在每月的基础上识别顶级投票获得者。我有一个可以工作的系统,但是对于rails来说是新手,我确信有更高效的方法可用。下面是我的当前设置(略控制器代码)的简化版本:Ruby on Rails - 每月顶级投票获取者
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
我将使用“只要”宝石运行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)}
我敢肯定有很多方法可以做到这一点更好,希望得到一些建议。如果您对建立投票表/关联的更好方式有任何建议,那也是值得赞赏的。
由于提前, CRS
只能有一个赢家吗?它看起来像你的代码处理关系。 – 2013-03-11 01:22:36
可以有多个获胜者。 cron工作将在每月的第一天运行。我会调整它只计算在上个月投出的选票。 – Clay 2013-03-11 01:30:26