Ruby on rails rails中的“new”和“build”有什么区别?

Ruby on rails rails中的“new”和“build”有什么区别?,ruby-on-rails,Ruby On Rails,我不理解这一行代码: @club = current_user.clubs.build(club_params) 我知道可以使用new方法创建相同的代码,然后我们可以保存实例变量,但是build在这种情况下做什么?new用于特定模型的新实例: foo = Foo.new build用于在AR关联中创建新实例: bar = foo.build_bar # (has_one or belongs_to) 或 更新 build和new是中定义的别名: 因此,如果类Foo有许多条,则以下内容具

我不理解这一行代码:

@club = current_user.clubs.build(club_params)

我知道可以使用
new
方法创建相同的代码,然后我们可以保存实例变量,但是
build
在这种情况下做什么?

new用于特定模型的新实例:

foo = Foo.new
build用于在AR关联中创建新实例:

bar = foo.build_bar  # (has_one or belongs_to)

更新

build和new是中定义的别名:

因此,如果类Foo有许多条,则以下内容具有相同的效果:

  • foo.bar.new
    foo.bar.build
  • Bar.where(:foo\u id=>foo.id)。新建
    Bar.where(:foo\u id=>foo.id)。构建
如果
!foo.新记录?

  • foo.Bar.new
    Bar.where(:foo\u id=>foo.id)。new

根据文档,New和build与之相同
ActiveRecord::Relation#build
在早期版本的Rails中的工作方式略有不同,但现在
build
只是
New
的别名。
bar = foo.bars.build # (has\_many, habtm or has_many :through)