1

My js.erb file won't appear in Rails 3.1.2 and it's really confusing me. I'm including it in app/views/items. I have this:

respond_to do |format|
  format.html { render :action => :index }
  format.js {render :content_type => 'text/javascript' }
end

and it's named correctly. I've tried different combinations of names, but I don't even understand how the js.erb gets included because it's not in my source code. I put an alert('hello'); in the js.erb and it won't run.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Roy
  • 3,574
  • 2
  • 29
  • 39
  • I can see the js file if I go to localhost/items/index.js. It's not included though – Roy Dec 05 '11 at 19:04

1 Answers1

2

If the js.erb is the same name as the controller action, and request.xhr? is true, then it will automatically render the js.erb. In the respond_to block, remove the code after format.js so that it looks like:

respond_to do |format|
  format.html { render :action => :index }
  format.js
end

Just be sure that the link activating this has remote => true, for example link_to 'Some action', some_action_path, :remote => true.

Sean Hill
  • 14,978
  • 2
  • 50
  • 56
  • If I press control +u, should I be able to see a link to the js file? – Roy Dec 05 '11 at 20:09
  • If you're talking about the rendered `link_to` links, then no. You will see a link to your controller. Once you click on that link, you will see javascript returned and executed. You can change the behavior of callbacks. I gave an example of how to do that here: http://stackoverflow.com/a/8197130/367611. – Sean Hill Dec 05 '11 at 20:29