Ruby on rails 在rails中使用作用域进行过滤
我试图使用ActiveRecord作用域创建一个记录过滤系统,但是我被困在同一个模型中有两个过滤器的地方。我正在尝试筛选具有Ruby on rails 在rails中使用作用域进行过滤,ruby-on-rails,ruby,activerecord,filtering,Ruby On Rails,Ruby,Activerecord,Filtering,我试图使用ActiveRecord作用域创建一个记录过滤系统,但是我被困在同一个模型中有两个过滤器的地方。我正在尝试筛选具有品牌标识:1和品牌标识:2 我的产品模型定义了品牌范围,如下所示: class Product < ActiveRecord::Base belongs_to :brand scope :brand, lambda{|brand| where('brand_id = ?', brand )} end class CategoriesController &
品牌标识:1
和品牌标识:2
我的产品
模型定义了品牌
范围,如下所示:
class Product < ActiveRecord::Base
belongs_to :brand
scope :brand, lambda{|brand| where('brand_id = ?', brand )}
end
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
<% @products_by_category.each do |product| %>
<h2><%= product.name %></h2>
<% end %>
categories/show
视图如下所示:
class Product < ActiveRecord::Base
belongs_to :brand
scope :brand, lambda{|brand| where('brand_id = ?', brand )}
end
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
<% @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?&brand=1&brand=4
并且查询的数组仅使用brand=1
进行过滤。我想用这两个参数对结果进行过滤。生成的url是否正确,或者应该是:
http://localhost:3000/categories/1?&brand=1,4
您提交的所有过滤器输入都具有相同的参数键,品牌
。因此,参数散列对于该键只能有一个值
您想使用复选框标记代替'brand\u id[]'
:
<%= check_box_tag 'brand_ids[]', brand.id, false, class: 'filter_check_box' %>
最后,这一点很重要,您不能通过GET操作向参数发送数组。你需要使用一个帖子。正如下面的第二个链接所指出的,这是HTTP的一个限制,而不是Rails
另见:
我谦恭地建议您使用更一致的名称来引用变量,以便于代码的可读性和维护。如果你使用的是一个品牌id,就像在那个产品范围内一样,那就称它为品牌id,而不是品牌 它仍然不工作,它将
品牌标识[]
作为单个参数传递,而不是品牌标识数组。参数不应该与作用域的名称匹配吗?在更仔细地查看了表单设置和您遇到的问题之后,我添加了一条关于获取发送参数限制的注释。您的第二个链接已通知我需要知道的内容,因此我将接受您的回答。太好了,很高兴我能提供帮助!