Laurent
Laurent

Reputation: 1584

js function not called by rails controller action - can't find why

I've trying to build a home.js.erb file to match my controller action home.html.erb

I built it, and made a simple alert call in the js but it doesn't show. When I copy/paste to another of my methods, the alert works.

I want js to work with my home action

The flow is: signin (via Facebook) => go home. No button calls the action "Home" because I use Facebook login, which runs via redirect on Javascript after FB logs the user in.

Here is the home action:

def home
    respond_to do |format|
        format.html
        format.js
    end 

end

And here is the home.js.erb:

$(function(){
alert("Hello");

});

And finally the routing around the controller, which is called session:

    resources :session 

   match '/signin', :to => "session#signin"
   match '/home', :to => "session#home"
   match '/logout', :to => "session#logout"
   match '/register', :to => "session#register"

Any help would be appreciated!

Upvotes: 2

Views: 453

Answers (1)

dorilla
dorilla

Reputation: 233

If I am understanding correctly, you want to fire the home.js alert when you enter home.html, right?

If this is the case, the way you built it will not work because home.js and home.html will not render simultaneously. i.e. when a user signs in, the controller will call home, with the format being html.

I suggest this:

place the following below all your javascript calls inside in the layout.

<%= yield :javascripts -%>

and in home.html.erb, add to the top:

<% content_for(:javascripts) do %>
  <script type='text/javascript'>
    <%= render :partial => 'session/home.js' %>
  </script>
<% end -%>

Note: since home.js.erb is now a partial, you'll have to rename this file :

_home.js.erb

Hope it helps!

Upvotes: 1

Related Questions