Mysql RubyonRails:在将模型中的记录列表返回控制器之前过滤它?
假设我有以下模型:Mysql RubyonRails:在将模型中的记录列表返回控制器之前过滤它?,mysql,ruby-on-rails,activerecord,filter,Mysql,Ruby On Rails,Activerecord,Filter,假设我有以下模型: class Computer < ActiveRecord::Base end 现在,我添加了一个功能来停用某些计算机,并按如下方式过滤停用的计算机: @computers = Computer.all class Computer < ActiveRecord::Base scope :not_deactivated, -> { where('deactivated IS NULL OR deactivated = ?', false
class Computer < ActiveRecord::Base
end
现在,我添加了一个功能来停用某些计算机,并按如下方式过滤停用的计算机:
@computers = Computer.all
class Computer < ActiveRecord::Base
scope :not_deactivated, -> { where('deactivated IS NULL OR deactivated = ?', false) }
end
此方法的问题是,我必须在所有控制器中添加未禁用的
是否可以在模型中执行此过滤,这样我就不必触摸控制器?在控制器中执行简单而常见的操作:
before_action :not_deactivated # , only [:index...]
private
def not_deactivated
@computers = Computer.where(your code)
end
由于控制器处理视图,您必须以某种方式启动对象。通过这样的过滤,您可以实现您现在使用模型过滤器尝试执行的操作 您可以通过声明
default\u scope
在每次调用您的计算机
模型时运行此操作
class Computer < ActiveRecord::Base
default_scope { where('deactivated IS NULL OR deactivated = ?', false) }
end
class计算机
因此,当您运行
计算机时,您得到的结果就是计算机。其中('deactivated为NULL或deactivated=?',false)
我认为不是。但是你可以在控制器上做一个“不”的动作。然后将未禁用的方法置于控制器的私有状态。
class Computer < ActiveRecord::Base
default_scope { where('deactivated IS NULL OR deactivated = ?', false) }
end