options_from_collection_for_select不允许按变量选择

时间:2016-02-27 02:34:40

标签: ruby-on-rails form-helpers

以下两段代码,options_from_collection_for_select用于在我使用设定值时设置:selected,但当我使用@posts.user_id时,它会失败。

为什么这有效?

select_tag "user-dropdown", options_from_collection_for_select(@users, 'id', 'fname', **11**), :class =>'form-control'

但这不是?

select_tag "user-dropdown", options_from_collection_for_select(@users, 'id', 'fname', **@posts.user_id**), :class =>'form-control'

1 个答案:

答案 0 :(得分:0)

select_tag "user-dropdown", options_from_collection_for_select(@users, 'id', 'fname', **@posts.user_id**), :class =>'form-control'

您试图在选项中显示的 @ posts.user_id 是什么?

带有options_for_select示例的

select_tag

使用option_for_select和select_tag

的示例
select_tag 'user_id', options_for_select(@users.collect{ |u| [u.name, u.id] })

这会生成以下内容:

<select id="user_id" name="user_id">
  <option value="1">Brad</option>
  <option value="2">Angie</option>
  <option value="3">Jenny</option>
</select>