LoginSignup
41
44

More than 5 years have passed since last update.

Railsでnewとbuildのちがい

Last updated at Posted at 2013-02-05

例えばブログアプリケーションを作成するために以下のようなアソシエーションを作ったとする。

$ rails g scaffold post title:string body:text
$ rails g scaffold comment post:references body:text

Commentのコントローラーには所属するpostをインスタンス変数に呼び出す。
フィルタを使う。

class CommentsController < ApplicationController
  before_filter :load_post

  def load_post
    @post = Post.find(params[:post_id])
  end

ここでお馴染みのnewメソッドでインスタンスを作成している

Comment.new

@post.comments.build

buildを使うと親モデルに対する外部参照キーを自動でセットできるらしい。
結構よく出てくるので覚えておく。

41
44
2

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
41
44