【发布时间】:2014-01-10 19:15:42
【问题描述】:
我有一个显示数据库中所有行程的索引页面。页面顶部是一个带有下拉列表的过滤器,您可以在其中选择类别、地区或两者来过滤结果。
当您选择您的选项并单击“显示”时,下拉菜单会返回到“所有类别”和“所有地区”的默认选项。
当我过滤结果时,如何才能让选定的选项显示在下拉列表中?
这是我的下拉菜单:
.row
= form_tag all_road_trips_path, id: 'filter-trips-form', method: :get do
.select-intro
Browse
.select-wrapper.trip-categories
= collection_select(:category, :id, Category.all, :id, :name, :prompt => "All categories")
.select-intro
trips for
.select-wrapper
= collection_select(:region, :id, Region.all, :id, :name, :prompt => "All regions")
.select-button
= submit_tag 'Show Trips', class: 'button square'
编辑::
我尝试添加selected 值并得到一个'undefined method `[]' for nil:NilClass' 错误。我认为这是因为我的下拉列表的第一个值是“所有类别”,实际上并不是数据库中的对象,因此缺少 id。这是更新的代码和服务器输出:
.row
= form_tag all_road_trips_path, id: 'filter-trips-form', method: :get do
.select-intro
Browse
.select-wrapper.trip-categories
= collection_select(:category, :id, Category.all, :id, :name, :prompt => "All categories", :selected => params[:category][:id])
.select-intro
trips for
.select-wrapper.trip-regions
= collection_select(:region, :id, Region.all, :id, :name, :prompt => "All regions", :selected => params[:region][:id])
.select-button
= submit_tag 'Show Trips', class: 'button square'
和
Started GET "/road-trips/all" for 127.0.0.1 at 2014-01-10 14:03:39 -0600
Processing by RoadTripsController#all as HTML
Category Load (0.4ms) SELECT "categories".* FROM "categories"
Rendered road_trips/_trip_filter.html.haml (4.7ms)
Rendered road_trips/all.html.haml within layouts/application (5.6ms)
Completed 500 Internal Server Error in 9ms
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
NoMethodError - undefined method `[]' for nil:NilClass:
app/views/road_trips/_trip_filter.html.haml:6:in `block in _app_views_road_trips__trip_filter_html_haml__2571960046883419269_70320079055780'
haml (3.1.8) lib/haml/helpers/action_view_mods.rb:162:in `block (2 levels) in form_tag_with_haml'
【问题讨论】:
标签: javascript jquery ruby-on-rails