论坛首页 入门技术论坛

学习 Agile Web Development with Rails“ 8.3 循环 C1: 创建个购物车”遇到的问题

浏览 3221 次
该帖已经被评为新手帖
作者 正文
   发表时间:2006-10-29  
刚刚学习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
   发表时间:2006-10-29  
请问如何解决?谢谢!!
0 请登录后投票
   发表时间:2006-10-31  
至少格式化一下代码吧?另外指出错在哪里行。埃。。。
这个注释里有复数问题:
引用
 
  def add_product(product)
    #  @items << LineItems.for_product(product)                       
    #  @total_price+=product.price
    # 
0 请登录后投票
   发表时间:2006-10-31  
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


class Cart
#get,set 方法的声明
  attr_reader:items
  attr_reader:total_price
  def initialize
    @items =[]
    @total_price=0.0
  end
  
  def add_product(product) 
    #  @items << LineItem.for_product(product)                        
    #  @total_price+=product.price
    #  
    item = @items.find{|i| i.product_id == product.id }#是这一行报错,报错:undefined method `find' for #<LineItem:0x6724bf0>

   
    if item
      item.quantity +=1     
    else
      @items = LineItem.for_product(product) 
      @items << item
    end
    @total_price+=product.price
  end
  
end
0 请登录后投票
   发表时间:2006-10-31  
谢谢!!
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics