您稍微误读了文档。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
集合中:
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">]
如果要通过关联创建对象,build
则应优先考虑new
构建,因为some_firm
即使在将任何对象保存到数据库之前,构建仍将内存中的对象(在这种情况下)保持一致的状态。