2

I have a couple action inside my cart_controller. I have 2 views inside /carts: payment.html.erb and pay.html.erb

def pay
   success = #do something that returns true or false
   if success
     respond_to do |format|
       format.html { redirect_to '/cart/checkout/review'}
     end
   else
     render_errors
   end
end

def render_errors
  respond_to do |format|
    format.html { render 'payment'}
  end
end

What i expect is that when

success == false

it hits render_errors and renders the payment view then stop. However what it's doing is: it's rendering the payment view AND THEN it renders the pay view as well. So the payment view is never shown. What am doing wrong? I'm using Ruby 2.0 on Rails 4.0.

UPDATE: I found out that whenever I do @cart.errors.add(:name, 'error message') the pay view is rendered regardless of any return or respond_to statements. Any idea?

manni
  • 717
  • 1
  • 9
  • 25

2 Answers2

6

I know this is a long ways ago, but for future Googlers!

Adding a return statement at the end of your respond_to block should do the trick!

def pay
   success = #do something that returns true or false
   if success
     respond_to do |format|
       format.html { redirect_to '/cart/checkout/review'}
     end
   else
     render_errors
   end
end

def render_errors
  respond_to do |format|
    format.html { render 'payment'}
  end and return  # here!
end
XML Slayer
  • 1,530
  • 14
  • 31
0

Don't simply call another action in current action, use redirect_to. The respond_to method registers formats like 'html', 'json' to the responder, but does not actually render it. Try this in your controller:

def pay
  success = #do something that returns true or false

  redirect_to action: 'render_errors' unless success

  respond_to do |format|
    format.html { redirect_to '/cart/checkout/review'}
  end      
end

or this:

respond_to do |format|
  if success
    format.html { redirect_to '/cart/checkout/review'}
  else
    format.html { redirect_to(:action => 'render_errors') }      
  end
end
tuo
  • 586
  • 1
  • 4
  • 20
  • 1
    i want to keep the context of my current `@cart` instance so i actually don't want to do a `redirect_to` since i'll lose all the instance values. – manni Nov 01 '13 at 19:21