【发布时间】:2017-02-27 14:51:17
【问题描述】:
假设我有以下模型:
class Computer < ActiveRecord::Base
end
然后我像这样检索控制器中的所有计算机:
@computers = Computer.all
现在我添加一个功能来停用某些计算机并过滤停用的计算机,如下所示:
class Computer < ActiveRecord::Base
scope :not_deactivated, -> { where('deactivated IS NULL OR deactivated = ?', false) }
end
在我的控制器中:
@computers = Computer.all.not_deactivated
这种方法的问题是我必须在我的所有控制器中添加not_deactivated。
是否可以在模型中执行此过滤器,这样我就不必触摸控制器了?
【问题讨论】:
-
我不相信。但是您可以在控制器顶部执行 before_action :not_deactivated 行。然后将 not_deactivated 方法放在控制器的私有中。
标签: mysql ruby-on-rails activerecord filter