My goal is to display a welcome message for the user after they create a new account and are redirected to their profile page; i.e., have the message be displayed on their profile page.
With the following code, I'm able to display the message but only for a split second - before the redirect occurs, which is nevertheless successful.
In my controller, I create the message and use an Ajax call to render my JavaScript template:
def create_user
# ...
@welcome_msg = "WELCOME"
format.js { render template: "layouts/message.js.erb" }
# ...
end
message.js.erb
$(window.location.replace("<%= profile_url %>"));
$("#welcome_message_placeholder").html("<%= j render partial: 'layouts/welcome_message', locals: { :user => @user, :welcome_msg => @welcome_msg } %>");
_welcome_message.html.erb
<%= @welcome_msg %>
application.html.erb
<div id="welcome_message_placeholder"></div>
What do I need to add/change to ensure that the user sees the message only after being redirected?
Turns out that one way to do this involves a slightly different approach from what I had above.
What I did (and what worked, thankfully) was I created a new flash
type in my users
controller that I then defined in all of my controllers (to avoid it being undefined in my application template) like so:
add_flash_types :custom_notice # included in all controllers
def create_user
# ...
format.js {render js: "window.location.href='#{profile_url}'"} # to replace message.js.erb
flash[:custom_notice]="WELCOME"
# ...
end
Now the message can essentially be treated as a traditional notice
in the base template, and the partial can be rendered directly (without a JS template middleman):
application.html.erb
<% if custom_notice %>
<%= render partial: "layouts/welcome_message" %>
<% end %>
_welcome_message.html.erb
<%= custom_notice %>
Note that add_flash_types
(registering custom flash types) isn't supported in Rails 3.