4

With Rails 3+ and the asset pipeline my understanding is that all the javascript files under assets/javascripts get automatically included and compiled into one js file if you specify

require_tree . 

in application.js.

What is the best practice regarding dealing with javascript that is specific to a controller/view? For example suppose I have a controller/view 'Houses' and I want to validate the houses form using the jquery form validation plugin, to do that I have placed the following code in my houses.js file

$(document).ready(function(){
  $("#new_house_form").validate();
});

which is fine but the problem is that when I visit another page (say /owners), it tries to validate the houses form and I get an error message in the javascript console. Ofcourse I could just check if the form exists on the current page or not and only then call the validator but that seems a little unclean to me esp if I have a lot of controller specific code in .ready.

My solution to work around this has been to create a folder assets/javascripts/global and in application.js

 require_tree ./global //instead of require_tree .

and move all the other js files except for houses.js in it. Then I manually include houses.js whenever the user accesses /houses/new or /houses/edit

Is this practice acceptable? If not what is considered to be the best practice to deal with these situations?

4-8-15-16-23-42
  • 286
  • 2
  • 7
  • Great solution here: http://stackoverflow.com/questions/7312465/how-to-display-controller-specific-javascript-in-rails-3-1 – agmin Oct 17 '12 at 18:15

1 Answers1

0

Usually I just let all the js get loaded and check if the element exists before calling any method on it.

$(document).ready(function(){
  if($("#new_house_form").length > 0){
    $("#new_house_form").validate();
  }
});
André Barbosa
  • 518
  • 4
  • 17
  • The problem with this is that if you have a lot of controller/view specific code (not just for forms) in your javascript then you are doing a lot of this kind of error checking. It's fine for the odd validation here and there but it gets pretty ugly as your javascript grows. I was hoping there would be a cleaner way to deal with this than manual error checks or the method I described in the question. – 4-8-15-16-23-42 Oct 18 '12 at 14:19
  • Yes, it's true that with this method you'll have a lot of error checking in your javascript. It's a quick fix for you problem. If you want a cleaner solution check the link that @agmin posted on his comment. Looks like a nice solution. – André Barbosa Oct 18 '12 at 17:48