【问题标题】:Ruby on Rails: Filter list of records in model before returning it to controller?Ruby on Rails:在将模型返回给控制器之前过滤模型中的记录列表?
【发布时间】: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


【解决方案1】:

在控制器中简单而常见的事情:

before_action :not_deactivated # , only [:index...]

private
def not_deactivated
@computers = Computer.where(your code) 
end

由于控制器处理视图,您必须以某种方式启动对象。通过这样的过滤,您可以使用模型过滤器实现您现在尝试做的事情。

【讨论】:

    【解决方案2】:

    您可以通过在每次调用 Computer 模型时声明 default_scope 来运行它

    class Computer < ActiveRecord::Base
      default_scope { where('deactivated IS NULL OR deactivated = ?', false) }
    end
    

    所以,当你运行Computer.all 时,你得到的结果是Computer.where('deactivated IS NULL OR deactivated = ?', false)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 2010-12-14
      • 2015-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多