Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby on Rails - Monthly top vote getter
    text
    copied!<p>I need some advice on a voting system in rails that recognizes the top vote getter on a monthly basis. I have a system that works but being new to rails, I'm sure there are more efficient methods available. Below is a simplified version of my current setup(controller code omitted):</p> <pre><code>class Charity &lt; ActiveRecord::Base has_many :votes end class Vote &lt; ActiveRecord::Base belongs_to :charity end </code></pre> <p>My schema is as follows:</p> <pre><code>ActiveRecord::Schema.define(:version =&gt; 20130310015627) do create_table "charities", :force =&gt; true do |t| t.string "name" t.text "description" t.date "last_win" t.datetime "created_at", :null =&gt; false t.datetime "updated_at", :null =&gt; false end create_table "votes", :force =&gt; true do |t| t.integer "charity_id" t.datetime "created_at", :null =&gt; false t.datetime "updated_at", :null =&gt; false end end </code></pre> <p>I'll be using the 'whenever' gem to run a cron job to determine the monthly winner and update the 'last_win' column of the charities table. The following code is where I'm questioning my efficiency:</p> <pre><code>vote_counts = Vote.count(:group =&gt; "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 =&gt; Date.today)} </code></pre> <p>I'm sure there are many ways to do this better and would appreciate some suggestions. If you have suggestions on better ways to set up the votes table / associations, that would be appreciated too.</p> <p>Thanks in advance, CRS</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload