2013-09-01 34 views
0

我的Rails应用程序需要做的所以他们实际上没有从数据库中移除灭活的某些记录“软”删除。目前我使用“is_deleted”标志来实现它。Rails的筛选出删除的记录在协会

我的问题是,是否有涉及该模型处理协会的最佳做法。例如:

class Foo 
    attr_accessible :is_deleted 
    scope :active, -> { where(is_deleted:false) } 
    belongs_to :bar 
end 

class Bar 
    has_many :foos 
end 

我想弄清楚如何设置酒吧模型,知道它通常只处理'积极'的foos。

我想出了一对夫妇的想法,并想知道是否有使用一个比其他任何优点/缺点。

  • 在has_many声明中使用“condition”限定符来筛选出已删除的项目。
  • 在Bar上创建一个“active_foos”方法,只返回未删除的项目。
  • 只需使用“acts_as_paranoid”宝石。它对我所需要的感觉有点重量级,但也许它是最简单的。

回答

2

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 
1

使用acts_as_paranoid第三个选项是最好的,因为它占据了大部分举重的同时也为您提供了其他选择加载所有记录是否删除或某些时间戳之后被删除。它更好地使用已经编写和测试的代码,然后自己重​​新发明轮子。

随着时间的周期,为您的应用程序的增长,您将需要在软删除的记录更&更多的选择和定制的查询。所以,去与acts_as_paranoid。