1

我有一个简单的 Rails 3 应用程序,其中一个目标有许多目标。在我看来,我允许用户对任何给定目标的目标重新排序,并且我正在使用acts_as_list gem 来实现其中的一些功能。

目标模型:

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

我还希望允许用户更改与特定目标相关联的目标。我会假设acts_as_list只要更改了目标的目标(因为我定义了scope => :goal),gem 就会重置位置列,但它只是保留当前位置。

对我来说,这是不可取的,因为在新目标的背景下,这个位置不再有意义。我宁愿重置位置,并将目标移动到与之关联的新目标的底部。所以我写了这个方法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不幸的是,当我尝试保存时,这会导致错误。关于如何解决这个问题的任何想法?

4

2 回答 2

3

好的,我最终将其重写reset_position为如下所示,因为acts_as_list显然不处理关联更改。

before_update :reset_position

def reset_position
  if self.goal_id_changed?
    self.position = self.goal.objectives.count > 0 ? self.goal.objectives.last.position + 1 : 1
  end
end

基本上,当它与不同的目标相关联时,它将目标移动到目标列表的底部。似乎工作。

于 2012-09-15T13:04:31.807 回答
0

我想说这是因为 move_to_bottom 自己试图保存记录。因此,在我看来,编写自己的这种方法版本将是可行的方法。从当前的acts_as_list 方法开始,并在不保存的情况下开发自己的变体。

于 2012-09-13T09:59:56.750 回答