Search code examples
ruby-on-railsselectformhelper

rails - How to set value of a select list from a variable?


I want to set the value in a select list based on the value of a variable.

The variable here is @email_setting.frequency. In the view the code looks like:

<%= select('email_setting', 'frequency','<option value="1">Daily</option>
                <option value="2">Immediately</option>
                <option value="3">Every Monday</option>
                <option value="4">Every Tuesday</option>
                <option value="5">Every Wednesday</option>
                <option value="6">Every Thursday</option>
                <option value="7">Every Friday</option>
                <option value="8">Every Saturday</option>
                <option value="9">Every Sunday</option>',
                :class=>'fl-space2 required size-120',
                :selected=>@email_setting.frequency) %>

I have tried few variations of the following with no luck.

Any advice on how to get this working right?

thanks


Solution

  • First check whether the value of @email_setting.frequency. Actually if you give 'email_setting', 'frequency' as the first 2 parameters, the selected value will be @email_setting.frequency. I believe it is actually integer(like 1) and you are providing string as the option value(like "1"). That should be the reason why it is not selected. Try

    <%= select('email_setting', 'frequency', [['Daily', 1],['Immediately', 2], ..], {}, :class=>'fl-space2 required size-120' %>
    

    Also the 4th parameter of select is options and the 5th parameter is html_options. So if you want to give html options like selected, class, you should provide it as 5th parameter by providing 4th parameter options as an empty hash. If you really want to give selected also, you should do that like this:

    <%= select('email_setting', 'frequency', [['Daily', 1],['Immediately', 2], ..], {}, :class=>'fl-space2 required size-120', :selected => @email_setting.frequency %>
    

    But the first would be enough in your case.

    See select rails api