43
50

More than 5 years have passed since last update.

buildメソッドについて

Last updated at Posted at 2018-03-27

親モデルに属する子モデルのインスタンスを新たに生成したい場合に使うメソッド。
(親モデルと子モデルは、アソシエーション設定あり)
外部キーに値が入った状態でインスタンスが生成できる。

ブログに紐づくコメントインスタンスを生成したい場合
※BlogモデルとCommentモデルは、1対多のアソシエーションを設定しているとします。

@blog = Blog.find(params[:id])
@comment = @blog.comments.build  ## 親モデル.子モデル.buildという形式

生成されるコメントインスタンスの中身

@comment
 id: nil,
 blog_id: 1,
 user_id: nil,
 content: nil,
 created_at: nil,
 updated_at: nil

blog_idに値が入っています。

43
50
0

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
43
50