【问题标题】:How do I create a scope to filter services by customer_category如何创建范围以按 customer_category 过滤服务
【发布时间】:2015-01-03 20:52:06
【问题描述】:

我有两个表/模型:客户和服务,我正在开发一个服务过滤器。

  • 这两个表之间的关系:一个客户“有很多”服务,一个服务“属于”一个客户。

  • 服务过滤器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 过滤具有特定客户的服务。

如何在 SQL 中将 Ruby/Rails 代码写成类似的东西:SELECT COUNT(*) FROMservicesWHERE (customer_id in (1, 2, 3))

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    如何在 SQL 中将 Ruby/Rails 代码写成类似的东西: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
    

    【讨论】:

    • 但是当我像这样运行范围时:Service.by_customer_category([1, 2, 3]),我得到:SELECT COUNT(*) FROM services WHERE (customer_id in 1, 2, 3),没有“()”,所以它不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多