Reputation: 2561
I am reading Agile Web Development with Rails. They have used the syntax:
item = cart.line_items.build(product_id: product_id)
My questions are:
What exactly is happening in the above statement? Which parts of the program are called? I couldnt find the detailed explanation.
why use build and then save instead of simply create?
Upvotes: 0
Views: 73
Reputation: 38772
Check the documentation to see how many auto-generated methods are injected into the Object when you define a has_many
relationship:
Among all of them it is the collection.build
.
1) This method is just a helper so you only need to write one line for something that otherwise would need more than one.
2) Not special reason, depends on the context, sometimes you only want to initialize the object and not save it yet. If you want to save the object just after initialization use the other auto-generated method collection.create!
Upvotes: 1
Reputation: 5239
The above line creates a new line_item associated with the cart and is initialized with a product_id. Build is essentially a nice bit of DSL that lets you leverage already existing relationships for creating new objects. It is just utilizing the has_many: :line_items
relation in the cart and the standard Object.new
The advantage to this approach is that you get the association with the cart for free instead of doing:
line_item = LineIten.new
line_item.cart = cart
line_item.product_id = product_id
Upvotes: 2
Reputation: 8006
The has_many :association_name
method, when called in a model definition, creates several methods, one of which is the .association_name
method, which makes a SQL query selecting all objects in that association.
To learn more about this, go to your terminal, type rails c
, and you can start playing around with how this works.
Upvotes: 1