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.)