Reputation: 10862
I am trying to assign a field in an ActiveRecord model (pos), to a value 1+ the highest value so far. The following, in either version, produces an infinite loop. I can't figure out why. Can you see it?
class Question < ActiveRecord::Base
attr_accessible :text, :pos, :data_type, :active
has_many :values
belongs_to :program
after_initialize :assign_pos
def row_label
text
end
def self.highest_pos
self.order("pos DESC").first
end
def assign_pos
puts "********* #{Question.highest_pos + 1}" # option 1
self.pos = Question.highest_pos + 1 # option 2
end
end
Upvotes: 0
Views: 267
Reputation: 21863
Your assign_pos
method is actually initializing self.pos
, so because of the after_initialize
condition, assign_pos
gets called again, and initializes self.pos
...
Upvotes: 2
Reputation: 2746
"self.order..." is actually selecting the object from the database, and calling initialize. After initialize it is calling assign_pos, which calls highest_pos, which starts everything all over again.
Upvotes: 1