我需要一些关于 Rails 投票系统的建议,该系统每月都会识别出票数最高的人。我有一个可以工作的系统,但对 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
我将使用 'whenever' gem 运行一个 cron 作业来确定每月获胜者并更新 charities 表的 '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