【发布时间】:2013-03-11 00:52:07
【问题描述】:
我需要一些关于 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
【问题讨论】:
-
可以只有一个获胜者吗?看起来你的代码处理了关系。
-
可以有多个获奖者。 cron 作业将在该月的第一天运行。我会将其调整为仅计算上个月的投票。
标签: ruby-on-rails ruby ruby-on-rails-3.2 voting favorites