您錯誤地閱讀了文檔。 some_firm.client.new
正在從客戶端集合中創建一個新的Client
對象,因此它可以自動將firm_id
設置爲some_firm.id
,而文檔則調用Client.new
,它根本不知道任何公司的標識,因此它需要將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
(在本例中)保持一致的狀態。
尋找快速回答的人,請檢查下面的第二個:「構建」只是「新」的別名 – ivanreese 2016-01-21 18:28:20