Rails 上的 build 和 new 有什么区别? [英] What is the difference between build and new on Rails?
本文介绍了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.new
build 用于在 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)
http://api.rubyonrails.org/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 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文