1

我有多个具有许多关联的类将它们链接在一起,我希望能够获取顶级对象,关闭它,并关闭所有子对象。我需要关闭每个对象,因为我希望能够选择任何父对象并关闭它的所有子对象。

例如(我意识到这可能不存在):

class Requisition
  has_many :shipments, :dependent_method => :close
end

class Shipment
  belongs_to :requisition

  has_many :reroutes, :dependent_method => :close
end

class Reroute
  belongs_to :shipment

  has_many :deliveries, :dependent_method => :close
end

class Delivery
  belongs_to :reroute
end

有人知道实现这一目标的好解决方案吗?宝石/插件是完全可以接受的:-)

非常感谢!

4

3 回答 3

0

很难理解你的目标。如果您能澄清“关闭”的含义,这将有所帮助。

以下信息可能会回答您的问题。

ActiveRecord 具有通过'save' 和'save!' 持久化到数据库的概念。方法。默认情况下,保存父对象时会保存关联对象。

于 2009-06-05T02:52:27.690 回答
0

如果您从未使用 destroy 方法从数据库中实际删除一行,您可以覆盖 destory 方法来执行 dateClosed 然后我相信 :dependent => :destroy 只是调用相关对象的 destroy 方法

def destroy
   dateClosed = Date.today
end

class Requisition  has_many :shipments, :dependent => :destroy
于 2009-06-05T19:32:23.443 回答
0

我坐下来写了一个小插件来做到这一点。我称之为它acts_as_closable,它只是将以下方法添加到before_save过滤器中。您必须为:autosave => true您希望它使用的每个关联使用 ,但这对我来说是有意义的,而不是acts_as_closable自动为您保存关联。稍后我可能会选择它并发布代码。这是肉:

def update_closed_status_of_children
  [self.class.reflect_on_all_associations(:has_many), self.class.reflect_on_all_associations(:has_one)].flatten.each do |assoc|

    # Don't consider :through associations since those should be handled in
    # the associated class
    if not (assoc.options.include? :through)
      attribute = self.class.acts_as_closable_config.closed_attribute
      children = self.send(assoc.name)
      children = Array(children).flatten.compact

      children.each do |child|
        # Check to make sure we're only doing this on something declaring acts_as_closable
        if child.class.included_modules.include? ActsAsClosable
          child.send(:closed_value=, self.closed_value)
        end
      end
    end

  end
end

我定义了一些其他方法(例如:closed_value=and :closed?),但这是我必须弄清楚的主要代码。希望它可以帮助别人!

于 2009-06-09T14:06:04.603 回答