سؤال

I have a data model that contains the fields for startMonth and endMonth. I also am able to SET them correctly using the following f.select tags, however, when I go to edit the data, the rendered dropdowns do not reflect the proper values stored in the db. Am i setting the f.select tags incorrectly?

<div class="control-group">
  <%= f.label "Start Month", :class => 'control-label' %>
  <div class="controls">
    <%= f.select :startMonth, options_for_select([['January' ,'1'],['February' ,'2'], ['March', '3'],['April' ,'4'], ['May', '5'],['June' ,'6'],['July' ,'7'], ['August', '8'],['September' ,'9'], ['October', '10'],['November' ,'11'], ['December', '12']]), class: "list-select" %>
  </div>
    <%= f.label "End Month", :class => 'control-label' %>
  <div class="controls">
    <%= f.select :endMonth, options_for_select([['January' ,'1'],['February' ,'2'], ['March', '3'],['April' ,'4'], ['May', '5'],['June' ,'6'],['July' ,'7'], ['August', '8'],['September' ,'9'], ['October', '10'],['November' ,'11'], ['December', '12']]), class: "list-select" %>      
  </div>
</div>

Once the data is stored using these dropdowns, it stores it correctly in the database and it shows the correct values on my show page. However, I want the dropdowns to default to the stored values when I return to the edit page. Is there a setting I am forgetting to include?

Alex

هل كانت مفيدة؟

المحلول

You can pass a second argument to the options_for_select method to pre-select the value. For example, assuming your model object is represented by an instance variable called @object, you can pass in @object.endMonth as the second parameter to your options_for_select.:

<%= f.select :endMonth, options_for_select([['January' ,'1'],['February' ,'2'], ['March', '3'],['April' ,'4'], ['May', '5'],['June' ,'6'],['July' ,'7'], ['August', '8'],['September' ,'9'], ['October', '10'],['November' ,'11'], ['December', '12']], @object.endMonth), class: "list-select" %>

Note: the @object.endMonth value must resolve to the same data type as the option value - in this case the number representing the month. See the Rails Guide for details.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top