Home > database >  Make select field selected based on params
Make select field selected based on params

Time:04-29

<%= select("category", "category_id", Category.all.collect { |p| [ p.title, p.id] },{include_blank: "All Category"},{class: "form-control"}  ) %>   

<div > 
  <%= button_tag( class: "btn btn-sm btn-outline-primary btn-rounded search-button-style") do %>
    <i ></i>
    <span><%= I18n.t 'search' %></span>
  <% end %>
</div>

I have a select field. I need to select the data based on params. I will be getting category_id in the params as params[:category][:category_id]

CodePudding user response:

Try this:

<%= select("category", "category_id", Category.all.collect { |p| [ p.title, p.id] }, { include_blank: "All Category", selected: params[:category][:category_id] }, { class: "form-control" }) %> 

The select method accepts selected in the options to choose one as selected.

This method is useful when generating a form for a model where it would autoselect the chosen option. You can also use select_tag like this if you wish:

<%= select_tag("category_id", options_for_select(Category.all.collect { |p| [ p.title, p.id] }, params[:category][:category_id]), include_blank: "All Category", class: "form-control") %> 

CodePudding user response:

With the parameter selected you can set the value which should be selected.

<%= select("category", "category_id", Category.all.collect { |p| [ p.title, p.id] },{include_blank: "All Category", selected: value},{class: "form-control"} ) %> 
  • Related