LoginSignup
53
63

More than 5 years have passed since last update.

Rails 新規作成formの作り方~newとbuildの違い~

Last updated at Posted at 2015-05-06

基本形

記事(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を使うほうがよさそうだ。

参考

Ruby on Rails 備忘録 – Ride On Rails

53
63
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
53
63