I'm using a form in my rails application, in my controller at the end I check if the content of the form is ok or not, if not I render the page again explaining on top the errors
part of controller
if @insertion.save
redirect_to @insertion
else
render 'new'
end
and in my view I've got this line to show the errors.
<% if @insertion.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(@insertion.errors.count, "error") %>.
</div>
<ul>
<% @insertion.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
the problem is that after the render the page will not load again my javascript file, so the view isn't as I expected
How can I force to reload js after render?
this is my coffee file due to turbolink
$(document).on "turbolinks:load", ->
insertionJS = new Insertion()
if $('.insertions.show').length > 0
console.log("insertions.show")
insertionJS.showJS() .....continue
With Turbolinks by design JavaScript and CSS are not reloaded, it turns your links etc. into XHR requests then uses the response to update
<body>
and trigger its special events (also why the jQuery$(function() { ... });
does not work as intended with Turbolinks. Since its doing an XHR, its not a real page load at all, even if it looks like one to the Rails controller.For most cases you can use
turbolinks:load
event like you showed, but that is not a magix solution, and you must still remember that all your "old" JavaScript and HTML still exists, that any JavaScript "globals" wont be reset, etc.If you want to be reloading/executing JavaScript on every page, just remove Turbolinks from your application (
Gemfile
,application.js
). If you implement proper cache headers for your CSS/JS and dont have too much JS, the performance difference is not that big.If you just want to disable it for a specific page/link/form for some reason, you can add the
data-turbolinks="false"
attribute to the link. Remember this needs to be on the link leading to the page, not the page itself. For the page itself to really reload, you could do likelocation.reload()
, but remember thats a complete seperate page reload after your render/redirect.If you really want to force JavaScript to reload, you could insert another
<script>
into head dynamically, but remember that your original JavaScript is still loaded, so thats likely to be a pain.Id note that Turbolinks is actually pretty large and complex, so it would be worth reading its own documentation rather than just the small snippets from Rails. https://github.com/turbolinks/turbolinks