Do you use Rails 4? (Find out by running rails -v in the console)
This issue is probably related to the recently added Turbolinks gem. This makes your application behave like a one-page JavaScript application. It has several advantages ( faster) , but unfortunately it breaks up some existing events, such as $(document).ready() , because the page never reloads. This explains why JavaScript works when you directly load the URL, but not when you go to it via link_to .
Here's the RailsCast about Turbolinks.
There are several solutions. You can use jquery.turbolinks as a fix to delete, or you can switch the $(document).ready() statement, use the Turbolinks 'page:change' event instead:
$(document).on('page:change', function() {
Alternatively, you can do something similar for compatibility with regular page loads, as well as with Turbolinks:
var ready = function() { // do stuff here. }; $(document).ready(ready); $(document).on('page:change', ready);
If you use Ruby on Rails> 5 (you can check by running rails -v in the console), use 'turbolinks:load' instead of 'page:change'
$(document).on('turbolinks:load', ready);
Ryan Endacott Jul 11 '13 at 17:55 2013-07-11 17:55
source share