1

I have the following class:

class Group < ActiveRecord::Base

  has_many   :users 
  belongs_to :leader, :foreign_key => "leader_id", :class_name => "User"

  def get_leader!
    if leader.try(:is_active?)
      return leader
    else
      leader = users.active.sort_by { |u| u.completed_sessions }.last
      save! # TODO: this does not save the new leader ... no idea why
      return leader
    end
  end    

end

When I call the get_leader! method it always returns the correct leader but fails to update the foreign_key 'leader_id' for the object.

As you can see from my actual code comment, I have no idea why. When I go to the console and explicitly set the leader for a group everything seems to work fine.

Does anyone understand why this would be?

(Incidentally, the purpose of the method is to update the leader of a group when the previous leader has become inactive. The new leader is the one with the most logins.)

Andy
  • 1,801
  • 3
  • 22
  • 33

1 Answers1

3

Try adding self in front of leader:

self.leader = users.active.sort_by{|u| u.completed_sessions}.last
save!

This is necessary in Ruby assignments, as Ruby doesn't know if leader is a variable local to that method, or an assignment method on the object self.

Also, if completed_sessions is a database column, I'd consider using this code to pull the correct user:

self.leader = users.active.order("completed_sessions DESC").first

This will sort the database using your database query, instead of pulling all records and having Ruby then sort them - more efficient when your user database gets bigger.

Rob d'Apice
  • 2,416
  • 1
  • 19
  • 29
  • Thanks. I used to just use self everywhere but then I saw fancy people leaving it out. Thanks for the clarification. Here is a good thread on the topic: http://stackoverflow.com/questions/4699687/when-to-use-self-foo-instead-of-foo-in-ruby-methods – Andy Jun 19 '12 at 05:28
  • Yep, complete_sessions is unfortunately not a database column but rather a method ... but good reminder. – Andy Jun 19 '12 at 05:38