#基本形
記事(article)の新規作成form(:title, :content, :image)
articles_controller.rb
def new
@article = Article.new
end
new.erb
<%= form_for @article do |f| %>
<p class="form-group field">
<%= f.label :title, class: "control-label" %>
<%= f.text_field :title, class: "form-control" %>
</p>
<p class="form-group field">
<%= f.label :content, class: "control-label" %>
<%= f.text_area :content, class: "form-control", rows => 6 %>
</p>
<p class="form-group field">
<%= f.label :image, class: "control-label" %>
<%= f.file_field :image %>
</p>
<% end %>
#親モデルと結びつける
記事(article)に紐づくコメント(comment)の新規作成(:content)
(ここではarticles/show内で新規作成)
@comment = @article.comments.build
@comment = Comment.new
を使う2通りがある。どちらでもできるが何が違うのだろうか。
まずは利用例から。
buildの利用
route.rb
resources :articles do
resources :comments do
end
end
articles_controller.rb
@article = Article.find(params[:id])
@comment = @article.comments.build #buildの利用
show.erb
<%= form_for [@article, @comment] do |f| %>
<p class="field form-group">
<%= f.label :content, class: "control-label" %>
<%= f.text_area :content, class: "form-control" rows => 6 %>
</p>
<p>
<%= f.submit "コメントする", class: "btn btn-primary" %>
</p>
<% end %>
newの利用
route.rb
#buildと一緒
resources :articles do
resources :comments do
end
end
articles_controller.rb
@article = Article.find(params[:id])
@comment = Comment.new #newの利用
show.erb
<%= form_for [@article, @comment] do |f| %>
<p class="field form-group">
<%= f.label :content, class: "control-label" %>
<%= f.text_area :content, class: "form-control" rows => 6 %>
</p>
<%= f.hidden_field :user_id, :value => @user.id #newで追加 %>
<p>
<%= f.submit "コメントする", class: "btn btn-primary" %>
</p>
<% end %>
buildとnewの違い
newはモデルのインスタンス生成でお馴染みである。buildも似ているが、外部参照キーを自動でセットしてくれるという点で異なる。つまり、親要素への結びつけが必要な場合ちょっと楽に出来る。(わざわざ、外部参照キーを自分で書く必要がない。)
よって、この場合buildを使うほうがよさそうだ。