【问题标题】:Filtering using Scopes in rails在 Rails 中使用 Scope 进行过滤
【发布时间】:2013-08-21 16:53:59
【问题描述】:

我正在尝试使用 ActiveRecord 范围创建记录过滤系统,但我被困在您有两个相同模型的过滤器的地方。我正在尝试使用brand_id: 1brand_id:2 过滤产品

我的Product 模型定义了brand 范围如下所示:

class Product < ActiveRecord::Base
  belongs_to :brand

  scope :brand, lambda{|brand| where('brand_id = ?', brand )}
end

我正在尝试过滤我的 categories/show 视图中的产品,而 CategoriesController 看起来像这样:

class CategoriesController < ApplicationController
  has_scope :brand

  def show
    @category = Category.find(params[:id])
    @products_by_category = apply_scopes(Product).where(category_id: @category).load
    @brands = @category.brands
  end
end

categories/show 视图如下所示:

<% @products_by_category.each do |product| %>
  <h2><%= product.name %></h2>
<% end %>

我正在使用此表单进行过滤:

<%= form_tag @category_path, method: get do %>
  <% @brands.each do |brand| %>
    <span class="filter_name"><%= brand.name%>:</span>
    <span> <%= check_box_tag :brand, brand.id, false,
                                     class: 'filter_check_box' %> </span>

   <% end %>
  <%=submit_tag 'filter'%>
<% end %>

问题是当我在复选框中选择多个品牌时,它只过滤第一个参数的产品;

例如,如果我使用 :id 1:id 2 过滤品牌并提交表单, 它的请求 url 看起来像这样:http://localhost:3000/categories/1?&amp;brand=1&amp;brand=4 并且查询的数组仅使用brand=1 过滤。我希望结果被两个参数过滤。结果 url 是否正确或应该是: http://localhost:3000/categories/1?&amp;brand=1,4 ?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord filtering


    【解决方案1】:

    您提交的所有过滤器输入都具有相同的参数键 brand。因此,参数散列只能具有该键的一个值。

    您想使用 check_box_tag 代替 'brand_ids[]'

    <%= check_box_tag 'brand_ids[]', brand.id, false, class: 'filter_check_box' %>
    

    最后,这很重要,您不能通过 GET 操作将数组发送到参数。您将需要使用 POST。正如下面的第二个链接所指出的,这是 HTTP 的限制,而不是 Rails。

    另见:

    一边

    我会谦虚地建议您使用更一致的名称来引用变量,以便于代码的可读性和维护。如果您使用的是品牌 ID,如在该产品范围内,请将其称为品牌 ID,而不是品牌。

    【讨论】:

    • 它仍然无法正常工作,它将brand_ids[] 作为单个参数而不是brand_ids 数组传递。参数不应该与作用域的名称匹配吗?
    • 在更仔细地查看了您的表单设置和您遇到的问题之后,我添加了一条关于 GET 发送参数限制的评论。
    • 您的第二个链接告诉了我我需要知道的内容,因此我会接受您的回答。
    • 太好了,很高兴我能帮上忙!
    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多