【问题标题】:What is the difference between build and new on Rails?Rails 上的 build 和 new 有什么区别?
【发布时间】:2010-11-18 05:08:00
【问题描述】:

谁能告诉我 Rails 上的 build 和 new 命令有什么区别?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    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

    更新

    根据@toklands 的建议,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

    【讨论】:

    • 确实如此,但缺少一件事:foo.bars.build 和 foo.bars.new 的区别(或等价物)。
    • 看起来和Rails中没有区别>3.2.6 stackoverflow.com/questions/4954313/build-vs-new-in-rails-3
    • 你能把你的旧答案和新的更新答案分开,也许可以指定版本吗?目前,它读起来就像你说了一件事,然后在没有任何明确通知覆盖或过时的情况下自相矛盾。
    【解决方案2】:

    在 Rails 2.2 之前,您需要为关系的 has_many/has_and_belongs_to_many 部分构建,以便新记录自动设置其外键。例如:

    user.timesheets.build
    

    将设置外键。我认为对于 rails 2.2 及更高版本,new 和 build 对 has_many 和 has_and_belongs_to_many 关系做同样的事情。

    【讨论】:

      【解决方案3】:
      【解决方案4】:

      在使用嵌套资源为视图表单创建“虚拟”对象时,我发现 .build 和 .new 之间存在差异。

      .build 创建一个 parent_id .new 没有

      嵌套资源示例: @list.items(其中 Item 嵌套在 List 下)

      @list.items.build ...生成一个除 list_id 之外的所有 nil 值的对象。

      Item.new 创建一个新的项目对象,所有的值为 nil。

      迭代@list.items 时,它出现在我的“显示”页面中 直到我需要@list.items 以另一种形式在同一个“显示”页面的下方进一步出现问题,@list.items 上的迭代暴露了具有关联 list_id 的项目(由 .build 生成的项目),但没有别的。

      下面的一些示例输出...

      @list.items.build => #


      2.2.3 :002 > Item.all.build => #


      2.2.3 :003 > Item.new => # 2.2.3:004 >

      【讨论】:

        【解决方案5】:

        曾经有一段时间 build 用新实例填充调用者,但 new 没有。现在从 Rails 4 new 和 build 用新实例填充调用者。如果您想了解一下,只需在控制台中玩转。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-08-02
          • 2011-11-22
          • 1970-01-01
          • 2018-06-04
          • 2021-08-26
          • 2017-10-31
          • 2012-12-29
          • 1970-01-01
          相关资源
          最近更新 更多