Instantiating a model with association
I have a question regarding instantiating a model with a belongs_to association.
Taken from the start of http://guides.rubyonrails.org/association_basics.html :
class Customer < ActiveRecord::Base
has_many :orders, :dependent => :destroy
end
class Order < ActiveRecord::Base
belongs_to :customer
end
This instantiation works:
@order = @customer.orders.cr开发者_如何学Ceate(:order_date => Time.now)
But would this work just as well?
class Order < ActiveRecord::Base
attr_accessible :customer
belongs_to :customer
end
@customer = Customer.new
@order = Order.create(:customer => @customer)
My experiments indicate that it does, to some extent.. But since associations are loaded lazily, it might be tricky in some cases (I can give one example, if you'd like).
So my question is: To what extent does that instantiation work just as well as the former?
These two forms both work.
Either way you have an Order object with a customer_id field set to the ID of an existing customer. When you call customer.orders.create() it's populating that association behind the scenes. In your second example you are doing it manually.
精彩评论