2011-11-08 64 views
1

我有一個評論和一個職位,其中郵政has_many評論和評論belong_to郵政。未設置select的Rails默認值?

在管理界面中,我有一個下拉菜單,用於選擇評論所屬的帖子。

下面是代碼:

<%= 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> 

但是,沒有被選中的選擇標籤默認值,即使它的文檔應該自動默認爲@comment.post_id中說。任何想法爲什麼沒有發生?

+0

它應該是'belongs_to'。這是一個錯字嗎? – fuzzyalej

+0

什麼是發射的HTML? – tadman

回答

3

如果您只是將數組作爲第二個對象而不是使用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) %>