182
105

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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をエイリアスにしている

こんな感じです。

以上です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?