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
Your
assign_posmethod is actually initializingself.pos, so because of theafter_initializecondition,assign_posgets called again, and initializesself.pos…