如何创建范围以按 customer_category 过滤服务

How do I create a scope to filter services by customer_category

我有两个 tables/models:客户和服务,我正在开发服务过滤器。

.col-sm-6
    - options_for_customer_select = Customer.uniq.order('name ASC').pluck(:name, :id)
    = label_tag :q, 'Customer:'
    = select_tag :by_customer_id, options_for_select(options_for_customer_select, params[:by_customer_id])
    scope :by_customer_category, -> customer_id { where("customer_id in ?", customer_id) }

在客户类别 select 输入中(在过滤器中),我想按客户类别的名称列出并使用 customer_id 来过滤具有特定客户的服务。

如何将 Ruby/Rails 代码写入 SQL 中的类似内容:SELECT COUNT(*) FROMservicesWHERE (customer_id in (1, 2, 3))?

How can I write Ruby/Rails code to something like that in SQL: SELECT COUNT(*) FROM services WHERE (customer_id in (1, 2, 3))?

您可以这样做:

Service.where(customer_id: [1,2,3]).count

如果你想让你的范围做到这一点,你必须使用这个:

scope :scope_name, -> (customer_ids){where(customer_id: customer_ids)}

如果将 where 参数中的 ? 替换为 (?):

,您的原始范围也将起作用
scope :scope_name, -> (customer_ids){where("customer_id IN (?)", customer_ids)}

然后你可以这样做:

Service.scope_name([1,2,3]).count