建立和新的on Rails的之间的区别是什么? [英] What is the difference between build and new on Rails?

查看:105
本文介绍了建立和新的on Rails的之间的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我什么是on Rails的构建和新的命令之间的区别是什么?

Can anyone tell me what is the difference between build and new command on Rails?

推荐答案

新是一个特定的模式的一个新实例:

new is for a new instance of a specific model:


foo = Foo.new

构建是内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)

<一个href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html">http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

每@ toklands的建议,建立和新的作为<一个定义的别名href="https://github.com/rails/rails/blob/959fb8ea651fa6638aaa7caced20d921ca2ea5c1/activerecord/lib/active_record/relation.rb#L84">ActiveRecord::Relation:

Per @toklands's suggestion, build and new are aliases as defined in ActiveRecord::Relation:

因此​​,如果类Foo的has_many酒吧,下面有同样的效果:

So if class Foo has_many Bars, the following have identical effects:

  • foo.bars.new &LT; => foo.bars.build
  • Bar.where(:foo_id =&GT; foo.id)。新&LT; => Bar.where(:foo_id =&GT; foo.id).build
  • 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 &LT; => Bar.where(:foo_id =&GT; foo.id)。新
  • foo.bars.new <=> Bar.where(:foo_id=>foo.id).new

这篇关于建立和新的on Rails的之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆