开发者

Trouble with order controller and active merchant

开发者 https://www.devze.com 2023-03-06 01:26 出处:网络
I\'m storing my shopping cart in the database and have a current_cart method in my application helper.

I'm storing my shopping cart in the database and have a current_cart method in my application helper.

 private

    def current_cart 
      Cart.find(session[:cart_id])
    rescue ActiveRecord::RecordNotFound 
      cart = Cart.create 
      session[:cart_id] = cart.id 
      cart
   end

Each cart has_many line_items. When a customer is ready to check out, they are sent to order/new ... when the order returns successful from the payment gateway though, everything is fine. But I'm testing the order failure and it seems there's a problem with my create con开发者_运维问答troller, because the @order object isn't being saved and rails is trying to render order#new again. It's not even getting to try and see if the payment was successful. I'm not sure what' wrong, as it was working when I tested it a few days ago.

def create
    @order = current_cart.build_order(params[:order])
    @order.ip_address = request.remote_ip

    @order.total_tokens = @order.calculate_total_tokens
    @order.user_id = current_user

      if @order.save
        if @order.purchase
         render :action => "success"
        else
          render :action => "failure"
        end
      else
        render :action => "new"
      end
   end

 def new
    @cart = current_cart
    if @cart.line_items.empty?
        redirect_to store_url, :notice => "Your cart is empty."
        return
    end

     @order = Order.new

     respond_to do |format|
       format.html # new.html.erb
       format.xml  { render :xml => @order }
     end
  end

I'm getting this error when it tries to render the page, obviously because the order hasn't been saved:

NoMethodError in Orders#create

Showing /Users/justin/Code/trackable/app/views/orders/_order_cart.html.erb where line #1     raised:

undefined method `line_items' for nil:NilClass
Extracted source (around line #1):

1: <% unless @cart.line_items.empty? %>
2: <div id="checkout_cart">
3: <% @cart.line_items.each do |l| %>
4:   <%= l.quantity %>

Not sure what's going on


So, adding @cart = current_cart to the #create controller seems to have fixed the problem. ActiveMerchant was throwing a validation error and for some reason, when it did that, it was losing @cart ... it wasn't doing that earlier when I was testing ActiveRecord validations, so I'm still not quite sure what I changed that screwed everything up.

0

精彩评论

暂无评论...
验证码 换一张
取 消