为什么会产生无限循环?

时间:2023-01-14 08:58:47

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?

我试图将ActiveRecord模型(pos)中的字段分配给目前为止最高值1+。在任一版本中,以下内容都会产生无限循环。我无法弄清楚为什么。你能看见它吗?

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

2 个解决方案

#1


2  

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

你的assign_pos方法实际上正在初始化self.pos,所以由于after_initialize条件,assign_pos再次被调用,并初始化self.pos ...

#2


1  

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

“self.order ...”实际上是从数据库中选择对象,并调用initialize。初始化之后,它调用assign_pos,它调用highest_pos,它会重新启动所有内容。

#1


2  

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

你的assign_pos方法实际上正在初始化self.pos,所以由于after_initialize条件,assign_pos再次被调用,并初始化self.pos ...

#2


1  

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

“self.order ...”实际上是从数据库中选择对象,并调用initialize。初始化之后,它调用assign_pos,它调用highest_pos,它会重新启动所有内容。