Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

Rails: Confused how tutorial is able to call line items object within method

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

line_items in the method will be executed as

self.line_items << item

here self will be referring to the instance of Order class

but in case of calling it from rails console it will try to find a local variable line_items that's why you are getting an error


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...