2

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!

0

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

4 Comments

Hi @dorilla, thanks a lot for this. I've been playing around with this and actually now realize that what I want is to have a div in my application header that shows the flash; and then set up my jquery script to update that div every time a flash is produced. This is a bit different from my initial query, but it makes sense for me to implement flash messaging at the same spot across the app.
No problem! Sounds good. Just curious, why not use rails's flash system?
Well the problem is, I run a search and produce the results in JS. So when there is an error (no results or a query limit reached) I need to produce the flash on the same page. My understanding is flash won't show until the next request, so I needed to implement via JS. Correct?
ahh ok right, this is separate from requests. ok cool. thanks for the accept!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.