我有一個索引頁面,顯示數據庫中的所有行程。頁面頂部是一個帶有下拉列表的過濾器,您可以選擇類別,區域或兩者來篩選結果。將下拉菜單重置爲選定的值
當您選擇您的選擇並點擊「顯示」時,下拉菜單將返回到「所有類別」和「所有區域」的默認選項。
當我過濾結果時,如何才能將選定選項顯示在下拉菜單中?
這裏是我的下拉菜單:
.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