我有一个索引页面,显示数据库中的所有行程。页面顶部是一个带有下拉列表的过滤器,您可以选择类别,区域或两者来筛选结果。将下拉菜单重置为选定的值
当您选择您的选择并点击“显示”时,下拉菜单将返回到“所有类别”和“所有区域”的默认选项。
当我过滤结果时,如何才能将选定选项显示在下拉菜单中?
这里是我的下拉菜单:
.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
值,得到一个 '未定义的方法`[]' 的零: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'
很好的解释。唯一的问题是,第一个提示'所有类别'或'所有区域'不是数据库中的类别或区域,所以它没有一个id。因此,当我尝试加载页面时,我得到了一个'未定义的方法'[]'nil:NilClass'。但是,如果已经做出选择,那么它会正常加载并按照您的解释工作。谢谢。 – reknirt
这不是导致该错误的原因。 :提示和:即使其中一个提示选项没有任何价值,也能很好地一起工作。如果你想要的话,你可以发布导致这个问题的视图代码以及回溯 – DiegoSalazar
的错误和前几行,我编辑了我的原始帖子。非常感谢。 – reknirt