我的rails应用程序需要对某些记录进行“软”删除,以便将其停用,而无需实际从数据库中删除它们。目前,我已经使用“ is_deleted”标志实现了它。
我的问题是,是否存在处理涉及此模型的关联的最佳实践。例如:
class Foo
attr_accessible :is_deleted
scope :active, -> { where(is_deleted:false) }
belongs_to :bar
end
class Bar
has_many :foos
end
我试图弄清楚如何设置Bar模型,因为它通常只处理“活动” foos。
我想出了几个主意,想知道是否有一个优点/缺点可以在另一个上使用。
techwineet的建议很不错。但是对于当前代码,最简单的解决方案是,如果需要经常处理,则将“活动”设置为默认范围。
class Foo
attr_accessible :is_deleted
default_scope -> { where(is_deleted:false) }
scope :active, -> { where(is_deleted:false) }
scope :deleted, -> { where(is_deleted:true) }
belongs_to :bar
end
class Bar
has_many :foos
# optional delegation
delegate :active, :delete, to: :foos, prefix: true
end
Foo.all #=> Return active foos. Or better to use Foo.scoped
Foo.deleted #=> Return all deleted foos
Foo.unscoped #=> Return all foos, both active and deleted
bar = Bar.first
bar.foos #=> Return associated active foos
bar.foos.active #=> Return associated active foos
bar.foos.deleted #=> Return associated deleted foos
bar.foos.unscoped #=> Return all associated foos
# Optional delegation
bar.foos_active #=> Return associated active foos
bar.foos_deleted #=> Return associated deleted foos
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句