Rails options_for_select 如何设置默认值?

puras · May 16, 2012 · Last by RobinWu replied at May 21, 2012 · 12800 hits

在修改页面,使用 options_for_select 来做下拉框 但是无法选择默认值,这个该如何处理呢?

<%= f.select :answer, options_for_select([['答案 A', 'A'], ['答案 B', 'B'], ['答案 C', 'C'], ['答案 D', 'D'], ['答案 E', 'E']]) %>

貌似:<%= f.select :answer, [['答案 A', 'A'], ['答案 B', 'B'], ['答案 C', 'C'], ['答案 D', 'D'], ['答案 E', 'E']] %> 这样也可以。但是还是没有默认值………………

后个参数吧,不记得了

唔。 如果使用 options_for_select。则使用: <%= f.select :answer, options_for_select([['答案 A', 'A'], ['答案 B', 'B'], ['答案 C', 'C'], ['答案 D', 'D'], ['答案 E', 'E']], @obj.answer) %>则可以了。 如果不使用 options_for_select,则使用<%= f.select :answer, [['答案 A', 'A'], ['答案 B', 'B'], ['答案 C', 'C'], ['答案 D', 'D'], ['答案 E', 'E']] %>这样便可以了。

options_for_select(container, selected = nil)

最后一个参数就是默认值,其实这类问题可以通过查阅 api 来解决

You need to Sign in before reply, if you don't have an account, please Sign up first.