LoginSignup
179
105

More than 5 years have passed since last update.

railsのnewとbuildの違い

Posted at

結論からいうと、ありません。

user = User.first
user.comments.new
=> #<Comment id: nil, body: nil, user_id: 1, created_at: nil, updated_at: nil>
user.comments.build
=> #<Comment id: nil, body: nil, user_id: 1, created_at: nil, updated_at: nil>

昔は、newだと上のuser_idが入らなかったみたいですね。

今はどちらも入るようになっています。

そのため、慣習的に関連するモデルを生成するときは、buildを使うようです。

User.new(user_params)
user = User.find(params[:id])
user.comments.build(comment_params)

ちなみにrailsのソースコード(5.1)です。

def build(attributes = {}, &block)
  @association.build(attributes, &block)
end
alias_method :new, :build  ←むしろnewをエイリアスにしている

こんな感じです。

以上です。

179
105
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
179
105