我有一个评论和一个帖子,其中帖子 has_many
评论和评论 belong_to
帖子。
在管理界面中,我有一个下拉菜单,用于选择评论属于哪个帖子。
代码如下:
<%= form_for @comment do |f| %>
<p>
<%= f.label :text, "Comment Text" %><br />
<%= f.text_field :text %>
</p>
<p>
<%= f.label "Post" %><br />
<%= f.select(:post_id, options_from_collection_for_select(Post.all, :id, :title), :include_blank => true) %>
</p>
<p>
<%= f.submit "Update" %>
</p>
但是,未选择 select 标签默认值,即使它在文档中说它应该自动默认为 @comment.post_id
。知道为什么这没有发生吗?
最佳答案
如果您只是将数组作为第二个对象而不是使用 options_from_collection_for_select
,Rails 只会自动使用 @comment.post_id
。这是 relevant documentation .所以如果你这样做,它会很好地工作:
<%= f.select(:post_id,
Post.all.collect {|p| [p.title, p.id] },
:include_blank => true) %>
如果您想坚持使用 options_from_collection_for_select
,那么您需要告诉它使用什么值作为选定值:
<%= f.select(:post_id,
options_from_collection_for_select(Post.all, :id, :title, @comment.post_id),
:include_blank => true) %>
关于ruby-on-rails - 未设置选择的 Rails 默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8055716/