简体   繁体   中英

In Ruby (2.2) on Rails How Do I Have A Confirmation Box Pop Up Then Redirect To Another Page

In my controller I have an if condition and I want an alert/confirmation box to pop up if it is satisfied, then when the user clicks "ok" to redirect to another page.

I've tried

flash[:alert] = 'Successfully checked in'
redirect_to check_in_path

However it just skips the alert part and goes straight to the redirect without an alert message.

My Ruby version is ruby 2.2.6p396 and rails is 5.0.1

Any help would be appreciated

you can do it as follows

  render :update do |page|
    page << "alert('Successfully checked in')"
    page.redirect_to check_in_path
  end

but partial rendering in controller is most commonly used together with Ajax calls. so you may have to make an ajax call to your action from your view page. Hope this will help you

Rails is limited to the respond to HTTP request with HTML. And what you describe sounds more like a JavaScript alert . What you tried, if configured properly*, will simply show the flash alert when the check_in_path page is rendered.

* Get familiar with how the flash works, Rails Guides

You have your controller set up correctly. The only other part I meant by configured correctly is that in your views you should display said flash message:

<% flash.each do |name, msg| -%>
  <%= content_tag :div, msg, class: name %>
<% end -%>

It's common to use the name of the flash to style it to make to make it's intent clear; commonly red for failure, green for success.

You need to create a js.erb file. You can then use your existing rails code along with a js alert box. Js.erb files let you combine rails and JavaScript code in the same file. As mentioned flash[:alert] is not an alert box, alert is a css class.

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