vendredi 4 janvier 2019

Rails: elsif && conditional statement in controller action not working

I am working on a multistep form, which is based on Ryan Bates' #217 Multistep Forms tutorial. I needed to implement conditional navigation inside the form and things became quite complex.

Navigation inside the form is working but I have problems with the conditions in my controller relative to the commit.

def create
  @order.current_step = session[:order_step]
  if @order.valid?
    if params[:back_button]
      @order.previous_step
    elsif params[:back_button_wiretransfer] && @order.payment = 'Wiretransfer'
      @order.payment_options_step
    elsif params[:back_button_credit_card] && @order.payment = 'Credit card'
      @order.creditcard_options_step
    elsif @order.thirdlast_step? && params[:commit] == 'Wiretransfer'
      @order.payment = nil
      @order.payment = 'Wiretransfer'
      @order.confirmation_step
    elsif @order.thirdlast_step? && params[:commit] == 'Credit card'
      @order.next_step
    elsif @order.secondlast_step?
      @order.payment = nil
      @order.payment = 'Credit card'
      @order.next_step
    elsif @order.last_step? && @order.payment = 'Wiretransfer'
      ...
    elsif @order.last_step? && @order.payment = 'Credit card'
      ...
    else
      @order.next_step
    end
    session[:order_step] = @order.current_step
  end
  if @order.new_record?
    render "new"
  else
    ...
  end
end

Currently the controller is not able to apply the last two elsif conditions with @order.payment = 'wiretransfer' or @order.payment = 'credit card'.

All other conditions are working, but when I checkout through the credit card section the wiretransfer part is executed.

When I use:

elsif @order.last_step? && @order.payment == 'Wiretransfer'
  ...
elsif @order.last_step? && @order.payment = 'Credit card'
  ...

'Credit card' works, but 'wiretransfer' does not. Since I display the payment attribute on the last step of the form I know it persists at that step although it wasn't saved yet to the database.

What am I doing wrong? I found out that sometimes I have to use = and other times ==, but the rational is not clear to me.

In the view I have to use == (comparison) such as in:

<% elsif @order.last_step? && @order.payment == "Credit card" %>

to trigger the right divs.

In the controller the two conditions

elsif @order.thirdlast_step? && params[:commit] == 'Wiretransfer' 
elsif @order.thirdlast_step? && params[:commit] == 'Credit card'

work only with ==, while all the others only with =. I started by using only == in the controller, but when I do so nothing gets executed and new is rendered.

Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire