在 Rails 中的每个查询中注入条件



我的一些模型有一个名为"company_id"的列。

我需要这些模型中的所有查询都具有基于此列的条件,以便我可以轻松地分隔公司行。

像这样:

Customer.where(state: x).`where(company_id: current_company)`...

如何拦截此方法以强制执行此额外条件?

我建议使用关注将此要求作为默认范围添加到所有模型。

module HasCompany
  extend ActiveSupport::Concern
  included do
    default_scope { where(company_id: current_company) }
  end
end
class Customer < ActiveRecord::Base
  include HasCompany
  ...
end

注意:仅当您有权访问current_company作为模型上的类方法时,此方法才有效。

这段代码在哪里?看起来像控制器逻辑?如果它位于控制器中,则只需在应用程序控制器的before_action中设置current_company — 可能就像您已经这样做一样。假设你在公司和客户之间有has_many关系,你应该做current_company.customers.where(state: x)

如果此代码存在于模型中,那就是事情变得棘手的时候。您不应有权访问模型中的current_company,因为这处理当前请求。

最新更新