这行代码看不懂:
@club = current_user.clubs.build(club_params)
我知道可以用new
方法创建相同的代码,然后我们可以保存实例变量,但是build
在这种情况下是做什么的呢?
最佳答案
new 用于特定模型的新实例:
foo = Foo.new
build 用于在 AR 关联中创建新实例:
bar = foo.build_bar # (has_one or belongs_to)
或
bar = foo.bars.build # (has\_many, habtm or has_many :through)
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
更新
build 和 new 是 ActiveRecord::Relation 中定义的别名:
所以如果类 Foo 有_many Bars,下面的效果是一样的:
foo.bars.new
<=>foo.bars.build
Bar.where(:foo_id=>foo.id).new
<=>Bar.where(:foo_id=>foo.id).build
<
如果 !foo.new_record?
foo.bars.new
<=>Bar.where(:foo_id=>foo.id).new
关于ruby-on-rails - rails中的 `new`和 `build`有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53701327/