建立新的VS Rails中3 [英] Build vs new in Rails 3

查看:116
本文介绍了建立新的VS Rails中3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails 3的文档,在建立的关联方法被描述为同为方法,但与外键的自动分配。直接从文档:

In the Rails 3 docs, the build method for associations is described as being the same as the new method, but with the automatic assignment of the foreign key. Straight from the docs:

Firm#clients.build (similar to Client.new("firm_id" => id))

我读过其他地方的类似。

I've read similar elsewhere.

然而,当我使用(如 some_firm.clients.new 不带任何参数),新的客户端的 firm_id 协会自动创建。我在盯着结果,现在在控制台中!

However, when I use new (e.g. some_firm.clients.new without any parameters), the new client's firm_id association is automatically created. I'm staring at the results right now in the console!

我缺少的东西吗?是的文档有点过时(不太可能)的?有什么的区别建立

Am I missing something? Are the docs a bit out of date (unlikely)? What's the difference between build and new?

推荐答案

您会略有误读文档。 some_firm.client.new 正在创造一个新的客户端从客户的集合对象,因此它可以自动设置 firm_id some_firm.id ,而文档呼吁 Client.new 它没有任何明确的id知识可言,所以它需要的 firm_id 传递给它。

You're misreading the docs slightly. some_firm.client.new is creating a new Client object from the clients collection, and so it can automatically set the firm_id to some_firm.id, whereas the docs are calling Client.new which has no knowledge of any Firm's id at all, so it needs the firm_id passed to it.

之间的唯一区别 some_firm.clients.new some_firm.clients.build 似乎是建立还增加了新创建的客户端向客户系列:

The only difference between some_firm.clients.new and some_firm.clients.build seems to be that build also adds the newly-created client to the clients collection:


henrym:~/testapp$ rails c
Loading development environment (Rails 3.0.4)
r:001 > (some_firm = Firm.new).save   # Create and save a new Firm
 => true 
r:002 > some_firm.clients         # No clients yet
 => [] 
r:003 > some_firm.clients.new     # Create a new client
 => #<Client id: nil, firm_id: 1, created_at: nil, updated_at: nil> 
r:004 > some_firm.clients         # Still no clients
 => [] 
r:005 > some_firm.clients.build   # Create a new client with build
 => #<Client id: nil, firm_id: 1, created_at: nil, updated_at: nil> 
r:006 > some_firm.clients         # New client is added to clients 
 => [#<Client id: nil, firm_id: 1, created_at: nil, updated_at: nil>] 
r:007 > some_firm.save
 => true 
r:008 > 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">] 

如果您通过关联创建一个对象,建立应pferred超过为$ P $打造让您的内存对象, some_firm (在这种情况下)保持一致的状态,即使之前的任何对象已经保存到数据库中。

If you're creating an object through an association, build should be preferred over new as build keeps your in-memory object, some_firm (in this case) in a consistent state even before any objects have been saved to the database.

这篇关于建立新的VS Rails中3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆