What does that line of code do?
I'm reading the book Agile web developement with Rails 4Th editon, when he present this method inside a model:
def add_line_items_from_cart(cart)
cart.line_items.each do |item|
item.cart_id = nil
line_items << item
end
end
and this is the explanation:
*For each item that we transfer f开发者_如何学Gorom the cart to the order we need to do two things. First we set the cart_id to nil in order to prevent the item from going poof when we destroy the cart. Then we add the item itself to the line_items collection for the order. Notice that we didn’t have to do anything special with the various foreign key fields, such as setting the order_id column in the line item rows to reference the newly created order row. Rails does that knitting for us using the has_many and belongs_to declarations we added to the Order and LineItem models. Append- ing each new line item to the line_items collection hands the responsibility for key management over to Rails.*
Can someone explain how this simple line of code line_items << item do all that stuff ?
Thanks for your attention Simone
Can someone explain how this simple line of code
line_items << item
do all that stuff?
That line doesn't do all that.
This could be better read like this:
def add_line_items_from_cart(cart) #<-- For each item that we transfer from the cart to the order we need to do two things
cart.line_items.each do |item|
item.cart_id = nil #<-- First we set the cart_id to nil in order to prevent the item from going poof when we destroy the cart.
line_items << item #<-- Then we add the item itself to the line_items collection for the order
end
end
The remaining:
Notice that we didn’t have to do anything special with... etc. etc
Is info about what the framework does. So, the description corresponds to the whole piece of code and not only to that line.
cart.line_items.each do |item|
-> takes every line_items from that cart and "gives them the name" item so you can make changes to them
item.cart_id = nil
-> sets the card_id of the item to nil
line_items << item
-> adds the item itself to the line_items collection for the order
line_items
is a list and line_items << item
adds an item to that list. item.cart_id = nil
clears out the Cart ID with the item, in case it was associated with a different Cart.
The book has already said It's Rails's work, line_items, belongs_to and has_many are the all things Rails needs. Inside of Rails, it help us to update the line_item.order_id.
精彩评论