Rails 上的 build 和 new 有什么区别?

编程入门 行业动态 更新时间:2024-10-27 22:26:36
本文介绍了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)

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 有什么区别?

本文发布于:2023-10-08 02:21:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471233.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   Rails   build

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!