Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set default value of form_for select

I would like to know how to set default value on form_for select.

My code goes like this:

<%= form_for(@user) do |f| %>
 .
 .
 .

 <div class="field">
 <%= f.select(:user_group_id, options_for_select(@user_groups.collect {|p| [ p.name, p.id ] },   "Select Category")) %>
 </div>
<%= end %>

Obviously it would return all the values of the field user_group. On my edit page, I would like to set the default value to whatever value the user have in the user_group. Pls help

like image 282
johan Avatar asked Mar 07 '11 01:03

johan


People also ask

How do I set default values for select options in SAP?

To assign default values to a selection criterion, you use the following syntax: SELECT-OPTIONS seltab FOR f DEFAULT g [TO h ].... Default values g and h can be literals or field names. You can only use fields that contain a value when the program is started.

How do you set the value of a select element?

Use the value property to set the value of a select element, e.g. select. value = 'new value' . The value property can be used to set or update the value of a select element. To remove the selection, set the value to an empty string.


2 Answers

You can pass a second option to options_for_select that indicates the selected value.

options_for_select(@user_groups.collect { |p| [p.name, p.id] }, @user.user_group)

Obviously I'm not sure how your models are set up, but if necessary you use a method like find to locate the entry you want.

like image 173
Michelle Tilley Avatar answered Sep 19 '22 12:09

Michelle Tilley


Add a parameter :selected =>

    <%= form_for(@user) do |f| %>
     .
     .
     .

     <div class="field">
     <%= f.select(:user_group_id, options_for_select(@user_groups.collect {|p| [ p.name, p.id ] },   "Select Category"), :selected =>f.object.user_group_id) %>
     </div>
    <%= end %>
like image 22
gavit Avatar answered Sep 21 '22 12:09

gavit