简体   繁体   中英

Rails: Stay on the same page after post action fails

I'm working on an order system, I passed some information about a new order from controller ( orders#confirm ) to a confirmation page using instance variable (such as @detail ). On the confirmation page, users are supposed to confirm the information and submit a form to create the new order ( orders#create ). If the post action fails, I want it to stay on the same confirmation page and preserve all the information on the page for the user:

  def create
    @order = Order.new(order_params)
    if verify_recaptcha(model: @order) && @order.save
      redirect_to items_url
    else
      render :confirm
    end
  end

The code is not working because all the variables that I passed from orders#confirm to the confirmation page are lost. I know I can recreate them, but is there any better ways to preserve those information? Thank you very much!

Within your approach, you have to rebuild the @detail object in the current action create in order to make your confirm.html.erb view to be rendered properly.

It is possible. However, I think there is a better way that you can let the user confirms the order by AJAX ( which is dead simple with Rails ) so the user can stay on the page if the confirmation failed.

In your confirm.html.erb , suppose you have a form to let user confirm, just change it to remote: true

<%= form_for @order, remote: true, format: :js do |form| %>
  <%# blah blah %>
<% end %>

Modify your controller

def create
  @order = Order.new(order_params)
  if verify_recaptcha(model: @order) && @order.save
    # Redirect when success
    render js: "window.location = '#{your_desired_path}'"
  else
    # Display error to user.
    render "ajax_create_error", status: :bad_request
  end
end

Now you can create a file name ajax_create_error.js.erb to display error to the user

# app/views/your_controller_name/ajax_create_error.js.erb
alert("Cannot create order");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM