本文介绍了Rails 上的 build 和 new 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能告诉我 Rails 上的 build 和 new 命令有什么区别?
Can anyone tell me what is the difference between build and new command on Rails?
推荐答案new 用于特定模型的新实例:
new is for a new instance of a specific model:
foo = Foo.newbuild 用于在 AR 关联中创建新实例:
build is for creating a new instance within an AR association:
bar = foo.build_bar # (has_one or belongs_to)或
bar = foo.bars.build # (has\_many, habtm or has_many :through)api.rubyonrails/classes/ActiveRecord/Associations/类方法.html
更新
根据@toklands 的建议,build 和 new 是 ActiveRecord::Relation:
Per @toklands's suggestion, build and new are aliases as defined in ActiveRecord::Relation:
所以如果类 Foo 有_many Bars,下面的效果是一样的:
So if class Foo has_many Bars, the following have identical effects:
- 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
更多推荐
Rails 上的 build 和 new 有什么区别?
发布评论