Rails options_for_select 如何设置默认值?

puras · 2012年05月16日 · 最后由 RobinWu 回复于 2012年05月21日 · 12737 次阅读

在修改页面,使用 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 来解决

需要 登录 后方可回复, 如果你还没有账号请 注册新账号