Dennis Nedry
Dennis Nedry

Reputation: 4747

How to build a rails form with a single parameter to flat hash

I have a rails-simpleform that looks like this:

=simple_form_for :search, url: search_path(:search), method: :get  do |f|
  = f.input :q
  = f.submit 'Search'

When I want to retrieve the input I have to access it with:

params[:search][:q]

Is it somehow possible to build the form in a way, that the parameters aren't nested under params[:search]? So that I can access them directly through params[:q]? I understand that this only makes sense if there is only a single input for a form.

CONTEXT:

What I'm trying to do is to allow the user to either search through the search-form described above or through a short-url(myapp.com/search-text).

Upvotes: 0

Views: 574

Answers (1)

Pablo
Pablo

Reputation: 3005

form_for (or simple_form_for) creates a form associated to a model object. The params passed to the controller add the model name as a key in the hash (params[:search][... fields_in_the_form ...]).

form_tag simply creates a form and it is not associated to any model. It does not add any key to the params hash except for the fields in the form. So this is a usual method to create search forms.

<%= form_tag(search_path, method: :get) do %>
  <%= text_field_tag :term, params[:search] %>
  <%= submit_tag 'Search', name: nil %>
<% end %>

Then you can use params[:search] in the controller.

Finally, to use myapp.com/search-text you should use route globing (http://guides.rubyonrails.org/routing.html#route-globbing-and-wildcard-segments) defining your route as:

get '*search', to: 'static_pages#search'

The StaticPagesController#search method will receive params[:search] with anything after myapp.com/. Note: this should be your last route, as it matches anything.

Upvotes: 1

Related Questions