【问题标题】:What is the difference between `new` and `build` in rails?rails中的`new`和`build`有什么区别?
【发布时间】:2018-12-10 07:40:13
【问题描述】:

这行代码看不懂:

@club = current_user.clubs.build(club_params)

我知道用new方法可以创建同样的代码,然后我们可以保存实例变量,但是build在这种情况下是做什么的呢?

【问题讨论】:

  • ActiveRecord::Relation#build 在早期版本的 Rails 中的工作方式略有不同,但现在 build 只是 new 的别名。

标签: ruby-on-rails


【解决方案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

更新

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

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 2010-11-18
    • 2018-08-02
    • 2018-06-04
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 2017-10-31
    相关资源
    最近更新 更多