我試圖在我的Rails應用程序中創建一個簡單的搜索表單。我得到一個錯誤與形式的URL路徑:未定義的局部變量或方法與form_tag
<%= form_tag(med_search, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search", class: "form-control" %>
<%= button_to "Search", class: "btn btn-default" %>
<% end %>
上面的第一行會導致錯誤undefined local variable or method
med_search」爲#<#:0x007fab2b5afa90>`
問題是最有可能與我的路線設置。我創建了一個新的控制器動作稱爲搜索,所以我編輯我routes.db看起來像這樣:
resources :meds do
collection do
get 'search' => 'meds#search'
end
end
devise_for :users
#get 'meds/index'
root to: "meds#index"
resources :meds, :path => ''
end
當我做耙路線,我看到了路徑檢索配有,所以我知道該網址是有效的:
Prefix Verb URI Pattern Controller#Action
med_search GET /meds/:med_id/search(.:format) meds#search
meds GET /meds(.:format) meds#index
POST /meds(.:format) meds#create
new_med GET /meds/new(.:format) meds#new
edit_med GET /meds/:id/edit(.:format) meds#edit
med GET /meds/:id(.:format) meds#show
PATCH /meds/:id(.:format) meds#update
PUT /meds/:id(.:format) meds#update
DELETE /meds/:id(.:format) meds#destroy
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
user_password POST /users/password(.:format) devise/passwords#create
new_user_password GET /users/password/new(.:format) devise/passwords#new
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
PATCH /users/password(.:format) devise/passwords#update
PUT /users/password(.:format) devise/passwords#update
cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel
user_registration POST /users(.:format) devise/registrations#create
new_user_registration GET /users/sign_up(.:format) devise/registrations#new
edit_user_registration GET /users/edit(.:format) devise/registrations#edit
PATCH /users(.:format) devise/registrations#update
PUT /users(.:format) devise/registrations#update
DELETE /users(.:format) devise/registrations#destroy
root GET / meds#index
GET / meds#index
POST / meds#create
GET /new(.:format) meds#new
GET /:id/edit(.:format) meds#edit
GET /:id(.:format) meds#show
PATCH /:id(.:format) meds#update
PUT /:id(.:format) meds#update
DELETE /:id(.:format) meds#destroy
我應該在路線中改變什麼來解決這個問題?
謝謝!
編輯:將網址更改爲med_search_path,得到新的錯誤:No route matches {:action=>"search", :controller=>"meds"} missing required keys: [:med_id]
。看起來像它涉及到/meds/:med_id/search(.:format)
嘗試在'form_tag'中將'med_search'替換爲'med_search_path',您需要在使用路由時追加'_path'。您還需要將'med_id'傳遞給操作或將成員之間的路由更改爲集合,具體取決於您的要求 – Athar
我認爲這可能是有效的,因爲現在我得到一個不同的錯誤:'沒有路由匹配{:action =>「search 「,:controller =>」meds「}缺少必需的鍵:[:med_id]'。我可以看到這與我的路線相符,但我不認爲我希望這樣設置。如何在我搜索之前更改路線,使其不需要med_id? – winston
要粘貼爲答案。不能在這裏寫太多的代碼。 – Athar