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

推荐答案

new用于特定模型的新实例:

foo = Foo.new

build用于在AR关联中创建新实例:

bar = foo.build_bar  # (has_one 或 belongs_to)

bar = foo.bars.build # (has\_many, habtm 或 has_many :through)

http://api.rubyonrails.或g/classes/ActiveRec或d/Associations/ClassMethods.html

Update

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

因此,如果Foo类有很多条,那么下面的效果是相同的:

  • foo.bars.new <=> foo.bars.build
  • Bar.where(:foo_id=>foo.id).new <=> Bar.where(:foo_id=>foo.id).build

And if !foo.new_rec或d?

  • foo.bars.new <=> Bar.where(:foo_id=>foo.id).new

Ruby-on-rails相关问答推荐

如何在_serialize之前执行代码?""或者如何在序列化属性之前对属性进行清理?

我使用rbenv安装Ruby,但我在使用";gem";->;错误:执行gem时遇到此错误.(Errno::EACCES)权限被拒绝

如何断言 Ruby 单元测试中的错误消息?

select2 未应用于所有下拉列表;它只适用于数据的最后一条记录

Rails 路由到唯一索引

在哈姆尔与当地人进行局部渲染?

如何使用 RSpec 和 Devise/CanCan 进行集成测试?

Rails 在关联模型中排序

什么是 Ruby 中的 Python 文档字符串?

Rails - 如何在 f.submit 上放置确认弹出窗口?

Rails 3.1 插件 gem、虚拟测试应用程序、rspec

为什么 respond_with 被从 rails 4.2 移除到它自己的 gem 中?

按周/月/等和 ActiveRecord 分组?

我如何在具有活动记录的 Rails 中使用两个不同的数据库?

在 Rails 协会中未找到名为的协会可能拼写错误的问题

如何在两个字段上对 ruby​​/rails 进行排序?

rake db:回滚不起作用?

在 GIT 中处理 Rails db/schema.rb 文件的正确方法是什么?

何时在 Ruby on Rails 中使用 lambda?

在 Rails 中显示主机名和数据库名