下订单时Rails交易错误

时间:2017-03-25 06:35:39

标签: ruby-on-rails ruby

我正在尝试与braintree支付宝石下订单,一切都工作正常,除了一件小事 我在下订单时遇到此错误

undefined method `total_price' for nil:NilClass

在order_transaction.rb文件中,该文件位于app / views / services / 这是文件

class OrderTransaction
    attr_reader :order,:nonce
    def initialize order, nonce
        @order=order
        @nonce=nonce
    end

    def execute
        @result = Braintree::Transaction.sale(
            amount: @order.total_price,
            payment_method_nonce: @nonce)
    end

    def ok?
        @result.success?
    end
end

这是orders_controller.rb中创建事务的方法

   def charge_user
        transaction=OrderTransaction.new @order,params[:payment_method_nonce]
        transaction.execute
        transaction.ok?
    end

我不知道发生了什么我在订购模型中使用方法total_price是这个

class Order < ApplicationRecord
  belongs_to :user
   has_many :order_items

    def total_price
        order_items.inject(0){|sum, item| sum +item.total_price }
    end
end

我还使用了attr_reader来读取order_transaction.rb文件中的顺序和nonce,为什么它为nil类显示未定义的方法我真的很困惑有人可以帮助我

这是控制器文件夹中的订单控制器

class OrdersController < ApplicationController
    before_filter :initialize_cart
    def create
        @order_form=OrderForm.new(user: User.new(order_params[:user]),cart: @cart)
        if @order_form.save
            notify_user
                if charge_user
            redirect_to products_path,notice:"Thank You for placing the order sir."
                end
        else
        render "carts/checkout",notice:"Something went wrong please try again."
        end
    end

    def custom
       @order_form=OrderForm.new(user: current_user,cart: @cart) 
          if @order_form.save
              notify_user
              if charge_user
            redirect_to products_path,notice:"Thank You for placing the order sir."
              end
        else
        render "carts/checkout",notice:"Something went wrong please try again sir."
        end
    end

   private

    def notify_user
      OrderMailer.order_confirmation(@order_form.order).deliver  
    end

    def order_params
        params.require(:order_form).permit(
            user:[:name,:phone,:address,:city,:country,:postal_code,:email])
    end

    def charge_user
        transaction=OrderTransaction.new @order,params[:payment_method_nonce]
        transaction.execute
        transaction.ok?
    end
end

0 个答案:

没有答案