【发布时间】:2011-11-24 07:13:51
【问题描述】:
我正在尝试通过下拉菜单(位置)和一组复选框(类别)过滤产品的索引页面,但效果并不好。我可以通过下拉列表过滤位置或类别。我也可以在一个表单中组合两个下拉菜单,但如果我无法为两个单独的表单找到可行的解决方案。
我想要实现的是提交 onchange 的位置下拉列表以及我想要作为带有过滤器按钮的复选框的类别。
我目前的代码提供了下拉菜单和复选框,但存在一些问题:
- 复选框列出了所有类别,但是当我根据这些进行过滤时,参数作为数组传递,但视图中没有返回任何产品
- 每当我按类别过滤时,我都会丢失之前的位置选择
以下是相关代码:
产品型号
....
has_many :categorizations
has_many :categories, :through => :categorizations
has_many :localizations
has_many :locations, :through => :localizations
class Product < ActiveRecord::Base
default_scope :order => 'end_date'
scope :not_expired, where('end_date > ?', Time.now)
scope :location, lambda { |*location_id| {:include => :locations, :conditions => ["locations.id = ?", location_id]} }
scope :category, lambda { |*category_id| {:include => :categories, :conditions => ["categories.id = ?", category_id]} }
scope :unique, :group => "title"
控制器
class LibraryController < ApplicationController
def index
if params[:location_id] && params[:category_ids]
@products = Product.not_expired.unique.location(params[:location_id]).category(params[:category_ids]).paginate(:page => params[:page], :per_page => 9)
elsif params[:category_ids]
@products = Product.not_expired.unique.category(params[:category_ids]).paginate(:page => params[:page], :per_page => 9)
elsif params[:location_id]
@products = Product.not_expired.unique.location(params[:location_id]).paginate(:page => params[:page], :per_page => 9)
else
@products = Product.not_expired.unique.paginate(:page => params[:page], :per_page => 9)
end
end
end
库 index.html.erb
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<div class="filter_options">
<form class="filter_locations", method="get">
<% @options = Location.all.map { |a| [ a.name, a.id ] } %>
<%= select_tag "location_id", options_for_select(@options), :onchange => "this.form.submit();", :include_blank => true %>
</form>
<form class="filter_categories", method="get">
<% for category in Category.all %>
<%= check_box_tag("[category_ids][]", category.id) %>
<%= category.name %>
<% end %>
<input type="submit" value="Filter" />
</form>
</div>
我一直在绕圈子,所以非常感谢任何方向。
为了部分回答我自己的问题,我修改了库索引并在类别表单中使用了一个隐藏字段,该字段调用 location_id 参数(如果存在),这意味着我可以保留选择类别后所做的任何位置选择复选框。
进一步的更新是我添加了一个检查是否通过查询参数来检查类别复选框,更新了下面的库 index.html.erb。
最后一次编辑与@rdvdijk 输入合并(谢谢)
库 index.html.erb
.......
<%= form_tag( '', :method => :get ) do %>
<% @options = Location.all.map { |a| [ a.name, a.id ] } %>
<%= select_tag "location_id", options_for_select((@options), params[:location_id]), :onchange => "this.form.submit();", :include_blank => true %>
<% end %>
<%= form_tag( '', :method => :get ) do %>
<% if(params.has_key?(:location_id)) %>
<%= hidden_field_tag 'location_id', params[:location_id] %>
<% end %>
<% Category.all.each do |category| %>
<%= check_box_tag 'category_ids[]', category.id, params[:category_ids].to_s.include?(category.id_to_s) %>
<%= category.name %>
<% end %>
<%= submit_tag 'Filter' %>
<% end %>
.......
【问题讨论】:
标签: ruby-on-rails checkbox filter params