我有多个类,多个关联将它们连接在一起,我希望能够获取顶级对象,关闭它,并关闭所有子对象。我需要关闭每个对象,因为我希望能够拾取任何父对象并关闭它的所有子对象。
例如(我意识到这可能不存在):
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有没有人知道一个好的解决方案来实现这个目标?gem/plugin是完全可以接受的:-)
非常感谢!
发布于 2009-06-09 14:06:05
我坐下来写了一个小插件来做这件事。我称它为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=和:closed?),但这是我必须弄清楚的主要代码。希望对其他人有所帮助!
发布于 2009-06-05 02:52:28
很难理解你的目标。如果你能澄清一下你所说的“关闭”是什么意思,那将会有所帮助。
以下信息可能会回答您的问题。
ActiveRecord的概念是通过“保存”和“保存!”来持久化数据库。方法。默认情况下,保存父对象时会保存关联对象。
发布于 2009-06-05 19:32:23
如果您从未使用销毁方法从数据库中实际删除一行,那么您只需重写销毁方法来执行销毁,然后我相信:dependent => :destroy只是调用相关对象的销毁方法
def destroy
dateClosed = Date.today
end
class Requisition has_many :shipments, :dependent => :destroyhttps://stackoverflow.com/questions/953303
复制相似问题