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.)
Try adding self in front of
leader:This is necessary in Ruby assignments, as Ruby doesn’t know if
leaderis a variable local to that method, or an assignment method on the objectself.Also, if
completed_sessionsis a database column, I’d consider using this code to pull the correct user: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.