我有两个表/模型:客户和服务,我正在开发服务过滤器。
这两个表之间的关系:客户'有很多'服务,服务'属于'客户。
服务过滤器html slim代码:
.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) }
在客户类别选择输入(在过滤器中),我想按客户类别的名称列出,并使用customer_id过滤具有特定客户的服务。
如何将Ruby / Rails代码编写为SQL中的代码:SELECT COUNT(*) FROM
services WHERE (customer_id in (1, 2, 3))
?
答案 0 :(得分:0)
如何将Ruby / Rails代码写入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