LoginSignup
0
1

More than 3 years have passed since last update.

Ruby buildメソッド

Posted at

buildメソッド

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

ユーザーに紐づくメモインスタンスを生成したい場合
※UserモデルとNoteモデルは、1対多のアソシエーションを設定しているとします。

note.controller.rb
 @note = current_user.notes.build(note_params)  ## 親モデル.子モデル.buildという形式

生成されるコメントインスタンスの中身
*pry-byebugで@noteインスタンスの中身を確認

 @note
 id: nil,
 title: "aaa",
 user_id: 2,
 category_id: 1,
 explanation: "ppppp",
 created_at: nil,
 updated_at: nil 

user_idに値が入っています。

0
1
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
0
1