Andy
Andy

Reputation: 1831

Rails assocation not saving

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

Upvotes: 1

Views: 49

Answers (1)

Rob d&#39;Apice
Rob d&#39;Apice

Reputation: 2416

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.

Upvotes: 3

Related Questions