I'm working through the book Agile Web Development 6th ed. In Task G, I am confused how line_items
is able to be called from the add_line_items_from_cart
method. The code is as follows:
class Order < ApplicationRecord
has_many :line_items, dependent: :destroy
def add_line_items_from_cart(cart)
cart.line_items.each do |item|
item.cart_id = nil
line_items << item
end
end
class LineItem < ApplicationRecord
belongs_to :order, optional: true
...
end
I fired up a rails console and when I run
c = Cart.last
c.line_items.each do |item|
item.id
line_items
end
I get
NameError (undefined local variable or method 'line_items' for main:Object)
Why is line_items
able to work in the method above, without prepending c.line_items
? And why doesn't it work when I run it in rails console?
question from:
https://stackoverflow.com/questions/65839140/rails-confused-how-tutorial-is-able-to-call-line-items-object-within-method 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…