LoginSignup
16
12

More than 5 years have passed since last update.

Ruby on Rails における build メソッドと new メソッドの違い

Last updated at Posted at 2018-06-23

結論

違いはない
buildnew のエイリアス

build - リファレンス - - Railsドキュメント

用途の違い

暗黙の了解で、モデルを関連付けしたときにbuildを使うみたいな感じになっているんですね。

とのこと
参照:newとbuildの違い - Qiita

メモ

1対多 子クラス生成 方法

TODO: それぞれ違いをまとめておきたい

# OK
thum = thumbnails.build(image: file)
thum.save!

# not reccomended
thum = Thumbnail.new(image: file)
thum.banner_id = self.id
thum.save!

# Also OK
thumbnails.create!(image: file)

# Also OK
thumbnails << Thumbnail.new(image: file)

参考

Rails4で1対多のリレーションをモデルに実装する - Rails Webook
【Rails入門】has_many、belongs_toの使い方まとめ | 侍エンジニア塾ブログ | プログラミング入門者向け学習情報サイト

16
12
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
16
12