user3437721
user3437721

Reputation: 2289

Rails - execute JS after a controller action

I have a login_controller which handles user logins. It uses single sign on - so the login is seemless to the user and they will be redirected to the page they were trying to access (e.g. for example if they had a link bookmarked).

I want to execute a js snippet for analytics. But I only want to execute it once, and that is after a login via the login_controller.

I tried adding a response header in the login controller:

response.headers['user_logged_in'] = "true"

and I put my JS in the application.html.erb to check for this header - but the header is not there:

if @user && request.headers['user_logged_in'] == "true"

Whats the best way to do this?

Upvotes: 1

Views: 78

Answers (1)

m26a
m26a

Reputation: 1413

I think your situation is perfect to use flash.

Anything you place in the flash will be exposed to the very next action and then cleared out.

So, you can do:

class SessionsController
  def create
    flash[:signed_in] = true
  end
end

Then, in your application.html.erb you can do:

<% if flash[:signed_in] %>
  ...
<% end %>

Upvotes: 3

Related Questions