我试图在我的Rails应用程序中创建一个简单的搜索表单。我在表单的url路径中出错:
<%= 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&#39;对于#&lt;#:0x007fab2b5afa90&gt;`
问题很可能是我的路线设置。我创建了一个名为search的新控制器操作,因此我编辑了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
当我做rake路线时,我看到路径med搜索,所以我知道网址是有效的:
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)
答案 0 :(得分:1)
1)您需要像这样更改form_tag
<%= form_tag(search_meds_path, :method => "get", id: "search-form") do %>
2)您需要将路线从member
更改为此类收藏
resources :meds do
collection do
get 'search' => 'meds#search'
end
end
3)不确定为什么需要再次在底部添加resources :meds, :path => ''
。如果您不需要它,最好删除。
答案 1 :(得分:0)
看起来您正在尝试对搜索进行编码,但由于您将其放在资源块中,因此Rails假设您正在讨论特定的med
。
从资源块中删除路线并将其更改为get 'meds/search' => 'meds#search'
。这将允许您将其用作常规端点,而Rails不会抱怨您需要ID。