学习 Agile Web Development with Rails“ 8.3 循环 C1: 创建个购物车”遇到的问题 WebRailsActiveRecordRuby
程序员文章站
2024-03-19 20:35:52
...
刚刚学习ruby,看书的时候,按照书上写例子出现问题,困扰我几天了:
执行add_product方法的时候,报错:undefined method `find' for #<LineItem:0x6724bf0>
class Cart
#get,set 方法的声明
attr_reader:items
attr_reader:total_price
def initialize
@items =[]
@total_price=0.0
end
def add_product(product)
# @items << LineItems.for_product(product)
# @total_price+=product.price
#
item = @items.find{|i| i.product_id == product.id }
if item
item.quantity +=1
else
@items = LineItem.for_product(product)
@items << item
end
@total_price+=product.price
end
end
class LineItem < ActiveRecord::Base
#告诉表的外键的表关系
belongs_to:product
def self.for_product(product)
item = self.new
item.quantity =1
item.product=product
item.unit_price = product.price
item
end
end
执行add_product方法的时候,报错:undefined method `find' for #<LineItem:0x6724bf0>
class Cart
#get,set 方法的声明
attr_reader:items
attr_reader:total_price
def initialize
@items =[]
@total_price=0.0
end
def add_product(product)
# @items << LineItems.for_product(product)
# @total_price+=product.price
#
item = @items.find{|i| i.product_id == product.id }
if item
item.quantity +=1
else
@items = LineItem.for_product(product)
@items << item
end
@total_price+=product.price
end
end
class LineItem < ActiveRecord::Base
#告诉表的外键的表关系
belongs_to:product
def self.for_product(product)
item = self.new
item.quantity =1
item.product=product
item.unit_price = product.price
item
end
end