我有一个包含startMonth和endMonth字段的数据模型。我也可以使用以下f.select
标记正确设置它们,但是,当我去编辑数据时,渲染的下拉列表不会反映存储在数据库中的正确值。我是否错误地设置了f.select标签?
<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>
使用这些下拉列表存储数据后,它会将其正确存储在数据库中,并在我的显示页面上显示正确的值。但是,当我返回编辑页面时,我希望下拉列表默认为存储的值。有没有我忘记包含的设置?
亚历
答案 0 :(得分:4)
您可以将第二个参数传递给options_for_select
方法以预先选择该值。例如,假设您的模型对象由名为@object
的实例变量表示,您可以将@object.endMonth
作为第二个参数传递给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" %>
注意:@object.endMonth
值必须解析为与选项值相同的数据类型 - 在本例中是表示月份的数字。有关详细信息,请参阅Rails Guide。