2015-08-19 43 views
0

完成本書使用Rails進行敏捷Web開發4.我試圖通過他們的沙箱API實現Paypal付款。但在創建訂單時請保持order上的錯誤。Rails使用Paypal模型未定義方法`訂單'

我有一個錯誤:未定義的方法order

class Order < ActiveRecord::Base 
    PAYMENT_TYPES = [ "Check", "Credit card", "Purchase order" ] 
    has_many :line_items, dependent: :destroy 
    # ... 
    validates :name, :address, :email, presence: true 
    validates :pay_type, inclusion: PAYMENT_TYPES 
    def add_line_items_from_cart(cart) 
    cart.line_items.each do |item| 
     item.cart_id = nil 
     line_items << item 
     puts line_items 
    end 
    end 

    serialize :notification_params, Hash 
    def paypal_url(return_path) 
    values = { 
     business: "[email protected]", 
     cmd: "_xclick", 
     upload: 1, 
     return: "#{Rails.application.secrets.app_host}#{return_path}", 
     invoice: id, 
     amount: order.line_items.price, 
     item_name: order.line_items.product.title, 
     item_number: order.line_items.id, 
     quantity: order.line_items.quantity, 
     notify_url: "#{Rails.application.secrets.app_host}/hook" 
    } 
    "#{Rails.application.secrets.paypal_host}/cgi-bin/webscr?" + values.to_query 
    end 

end 

,並從我的訂單控制器

# POST /orders 
    def create 
    @order = Order.new(order_params) 
    @order.add_line_items_from_cart(@cart) 

    respond_to do |format| 
     if @order.save 
     Cart.destroy(session[:cart_id]) 
     session[:cart_id] = nil 
     OrderNotifier.received(@order).deliver 
     format.html { redirect_to @order.paypal_url(order_path(@order)), notice: 
      'Thank you for your order.' } 
     else 
     format.html { render action: 'new' } 
     end 
    end 
    end 

enter image description here

NameError (undefined local variable or method `order' for #<Order:0xb59cca4c>): 
    app/models/order.rb:23:in `paypal_url' 
    app/controllers/orders_controller.rb:59:in `block (2 levels) in create' 
    app/controllers/orders_controller.rb:54:in `create' 
+0

你能不能請更新顯示錯誤行的日誌 – nik

+0

thks @nik我更新了這篇文章。第23行代表'amount:order.line_items.price',' –

+1

用行23中的self替換order以及order in paypal_url方法中的所有後續行。 – nik

回答

2

你需要調用self的屬性,因爲paypal_url一個inst Order類的對象上的ance方法,以及您的@order變量完全是:@order = Order.new(order_params)。確實在paypal_url方法中沒有order變量。

def paypal_url(return_path) 
    values = { 
     business: "[email protected]", 
     cmd: "_xclick", 
     upload: 1, 
     return: "#{Rails.application.secrets.app_host}#{return_path}", 
     invoice: id, 
     amount: self.line_items.price, 
     item_name: self.line_items.product.title, 
     item_number: self.line_items.id, 
     quantity: self.line_items.quantity, 
     notify_url: "#{Rails.application.secrets.app_host}/hook" 
    } 
    "#{Rails.application.secrets.paypal_host}/cgi-bin/webscr?" + values.to_query 
end