如何管理rails中相关模型的启用/不可启用状态



例如,假设我有一个位置和一个事件,它们的操作如下:

class Location < ActiveRecord::Base
has_many :events
default_scope  { where is_enabled: true }
end
class Event < ActiveRecord::Base
belongs_to :location
default_scope  { where is_enabled: true }
end

我遇到的问题是,我可能有启用的事件,但位置变得不启用。在这种情况下,我是否需要更新所有其他列来反映这一点(即将具有该特定位置的location_id的所有事件的is_enabled设置为false)。我正在考虑创建一个名为LocationManager的类,该类将具有一个称为Unable的方法,该方法将管理所有这些关系的启用和不启用。关于如何管理这个问题,还有其他想法吗?

如果给定Location实例上的is_enabled字段更改为false,则我将对Location进行回调,该回调将更新所有关联Event对象的is_enabled字段:

class Location < ActiveRecord::Base
has_many :events
default_scope  { where is_enabled: true }
after_update :disable_corresponding_locations, :if => lambda { self.is_enabled_changed? && self.is_enabled == false }
private
def disable_corresponding_locations
self.events.map {|event| event.update_attributes :is_enabled => false }
end
end
class Event < ActiveRecord::Base
belongs_to :location
default_scope  { where is_enabled: true }
end

通过这种方式,您可以在after_update上创建另一个回调,如果需要,它可以重新启用与Location关联的所有Event对象。

最新更新