《 rails 3》docs ,关联的 build
方法被描述为与 new
方法相同,但具有外键的自动分配。直接来自文档:
Firm#clients.build (similar to Client.new("firm_id" => id))
我在其他地方读过类似的内容。
但是,当我使用 new
(例如,不带任何参数的 some_firm.clients.new
)时,新客户端的 firm_id
关联 是自动创建的。我现在正在控制台中查看结果!
我错过了什么吗?这些文档是否有点过时了(不太可能)? build
和 new
之间有什么区别?
最佳答案
您稍微误读了文档。 some_firm.client.new
正在从客户端集合中创建一个新的 Client
对象,因此它可以自动将 firm_id
设置为 some_firm .id
,而文档正在调用 Client.new
,它根本不知道任何公司的 ID,因此需要将 firm_id
传递给它。
some_firm.clients.new
和 some_firm.clients.build
之间的唯一区别似乎是 build
还添加了新创建的客户端到 clients
集合:
(some_firm = Firm.new).save # Create and save a new Firm
#=> true
some_firm.clients # No clients yet
#=> []
some_firm.clients.new # Create a new client
#=> #<Client id: nil, firm_id: 1, created_at: nil, updated_at: nil>
some_firm.clients # Still no clients
#=> []
some_firm.clients.build # Create a new client with build
#=> #<Client id: nil, firm_id: 1, created_at: nil, updated_at: nil>
some_firm.clients # New client is added to clients
#=> [#<Client id: nil, firm_id: 1, created_at: nil, updated_at: nil>]
some_firm.save
#=> true
some_firm.clients # Saving firm also saves the attached client
#=> [#<Client id: 1, firm_id: 1, created_at: "2011-02-11 00:18:47", updated_at: "2011-02-11 00:18:47">]
如果您通过关联创建对象,则 build
应该优先于 new
,因为 build 会保留内存中的对象 some_firm
>(在本例中)即使在将任何对象保存到数据库之前也处于一致状态。
关于ruby-on-rails - Rails 3 中的构建与新建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4954313/