我有一個簡單的Rails 3應用程序,其中一個目標有很多目標。在我看來,我允許用戶爲任何既定目標重新排序目標,並且我正在使用gem來實現某些功能。使用acts_as_list gem時重置位置屬性? (Rails)
目標模式:
class Goal < ActiveRecord::Base
attr_accessible :name, :description
has_many :objectives, :order => :position, :dependent => :destroy
end
目標模式:
class Objective < ActiveRecord::Base
attr_accessible :name, :description, :position
belongs_to :goal
acts_as_list :scope => :goal
end
我也希望允許用戶改變特定的目標關聯的目標。如果目標的目標發生變化(因爲我定義了scope => :goal
),我會假設acts_as_list
寶石會重置位置列,但它只是保留當前位置。
對我而言,這是不可取的,因爲這個位置在新目標的背景下不再有意義。我寧願將位置重置,目標也會移動到與其關聯的新目標的底部。所以我寫了這個方法,在目標模型中的before_save
發生:
before_update :reset_position
def reset_position
if self.goal_id_changed?
self.move_to_bottom #acts_as_list method
end
end
不幸的是,這導致stack level too deep
錯誤,當我試圖保存。任何想法如何我可以解決這個問題?
另請參閱:http://stackoverflow.com/questions/13809105/sequence-numbers-in-rails#comment19001212_13809105 – ardochhigh
替代方案:'self.postion =(goal.objectivies.last.try(:position)|| - 1)+ 1' – Kris