2016-07-25 90 views
0

我有兩個模型發佈和評論。Rails:如何在新的動作中初始化實例變量

class Post < ActiveRecord::Base 
has_many :comments 
end 

class Comment < ActiveRecord::Base 
belongs_to :post 
end 

我爲創造新的評論形式如下

<%= form_for @comment , :url => post_comments_path(params[:post_id]) do |f| %> 
    <%= f.text_area :title %> 
    <%= f.submit "Add Comment" %> 
<% end %> 

我有上述形式的新的行動混亂。在新行動中,我可以用以下兩種方式初始化@comment實例變量。

@comment = Comment.new 

or 

@post = Post.find(params[:id) 
@comment = @post.comments.build(set_params) 

我的問題是Comment.new和@ post.comments.build(set_params)之間有什麼區別。

+0

第一條評論不會有'post_id'屬性集。這是全部的區別 –

+0

根據你如何處理評論的創建,一個或另一個形式可能是可取的。 –

回答

0

後者是首選,因爲它會在註釋上設置post_id

相關問題