Search code examples
javascriptruby-on-railsruby-on-rails-4turbolinks

Rails 4: Turbolinks redirect with flash


Lets say I have a standard controller create action:

def create
  @object = Object.new(object_params)
  if @object.save
    redirect_to @object, flash: {success: "Created object successfully."}
  else
    render :new
  end
end

Now if I change the redirect to use turbolinks:

redirect_to @object, turbolinks: true, flash: {success: "Created object successfully."}

the server returns a text/javascript response, and my browser is displaying it as a white page with just this line of text on it:

Turbolinks.visit('http:/localhost:3000/objects/1');

How do I make it so my browser actually executes that code instead of displaying it as text?

Also, how can I get the flash success message to appear?


Solution

  • This is how I ended up solving this using Turbolinks and materialize toasts for a great flash UX:

    In my controller:

    format.js {
      flash[:toast] = 'Created record successfully.'
      render :create
    }
    

    In create.js.erb:

    Turbolinks.visit("<%= success_path %>");
    

    In my _flash.html.erb partial:

    <% flash.each do |type, message| %>
      <% if type == "toast" %>
        <script id="toast">
          $(function() {
            Materialize.toast('<%= message %>', 3000);
          });
        </script>
      <% elsif type == "success" %>
        ...
      <% elsif type == "alert" %>
        ... 
      <% end %>
    <% end %>