2013-03-11 60 views
2

我需要一些关于投票系统的建议,这些投票系统可以在每月的基础上识别顶级投票获得者。我有一个可以工作的系统,但是对于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

+0

只能有一个赢家吗?它看起来像你的代码处理关系。 – 2013-03-11 01:22:36

+0

可以有多个获胜者。 cron工作将在每月的第一天运行。我会调整它只计算在上个月投出的选票。 – Clay 2013-03-11 01:30:26

回答

2

东西像这样:

如果只有一个赢家,这将工作我想

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) 

确保一切都在你的数据库索引正确,

你也许可以简化IT较多,但SQL将会变得更加复杂。

+0

感谢您的帮助。感谢您提醒我索引。 – Clay 2013-03-12 00:47:48

1

最后两行可能是:

Charity.where(id:winning_ids).update_all(last_win:Date.today) 

这将转化为一个SQL更新命令,而不是对每个获奖慈善机构发出的更新命令。

第一部分,你确定获胜的慈善机构看起来没问题,而且由于你将它作为cron工作运行,你可能不在乎是否需要几分钟时间。

不过,如果你想显示实时值,你可以在Vote添加after_create钩来更新计数器为它的主人慈善机构(可能在另一个表):

class Vote < ActiveRecord::Base 
    belongs_to :charity 
    after_create :increment_vote_count 
    CharityVote.where(year:Time.now.year, month:Time.now.month, 
    charity_id:self.charity_id).first_or_create.increment!(:counter) 
end