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">]
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.
build 与 new 的最大区别:
新的对象会在 collection 中,是这个样子吗?
reference http://stackoverflow.com/questions/4954313/build-vs-new-in-rails-3