pangpang
pangpang

Reputation: 8821

form_for doesn't get correct routes

I have a search form, but when I click the search button, it doesn't get the correct url:

<%= form_for search_leads_path, method: :get do %>
   <%= text_field_tag :search, params[:search] %>
   <%= submit_tag "Search" %>
<% end %>

it should be go to the /leads/search, but it is still in /leads

rake routes:

....
      search_leads GET    /leads/search(.:format)                                 leads#search
             leads GET    /leads(.:format)                                        leads#index
....

anyone has good idea? Thanks in advance!

Upvotes: 0

Views: 55

Answers (2)

Dharam Gollapudi
Dharam Gollapudi

Reputation: 6438

form_for expects the first argument be a resource, for example @user. Which works well for the Restful routes. But as this is a custom route, you should use form_tag instead.

Try updating your form logic to the following:

<%= form_tag search_leads_path, method: :get do %>
   <%= text_field_tag :search, params[:search] %>
   <%= submit_tag "Search" %>
<% end %>

Refer to FormTagHelper#form_tag for more info.

Upvotes: 1

LHH
LHH

Reputation: 3323

Try doing it like this -

first argument should be the object and then define your custom url.

<%= form_for(:search, url: search_leads_path, method: :get) do %>
  <%= text_field_tag :search, params[:search] %>
  <%= submit_tag "Search" %>
<% end %>

for more info check here http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for

Upvotes: 2

Related Questions