Jump to content

The ultimate community for Ruby on Rails developers.


javascript placement question

rails javascript

  • Please log in to reply
2 replies to this topic

#1 Vell



  • Members
  • 100 posts
  • LocationWashington, DC

Posted 03 March 2014 - 01:32 AM

Hello all,


I was curious about placement of javascript when it comes to code dealing with observing fields (or other scenarios that may apply). Take the following code for example:

    alert("this field as changed");

When I was learning rails, I was instructed to place code like this in my view. I wasn't told why aside from just being told that it wouldn't work if I placed this in the js assets file.This doesn't seem correct to me. If that were the case then why have the js assets file in the first place. Why couldn't this code be placed there and work just the same? 


I am curious how the rest of the world deals with code like this and what the rule of thumb is for it. And maybe my ultimate question would be, when is it appropriate to not use the js assets files for placing javascript code if ever? 

#2 danielhanke



  • Members
  • 12 posts
  • LocationCologne, Germany

Posted 03 March 2014 - 06:48 AM   Best Answer



placing JS code into a non-JS-View is always a bad idea. mixing languages in a single file actually is. 


You also get benefits from placing it into the assets: sprockets will compress and merge your files if you want to, the clients can cache these assets and your website will possibly  feel a lot faster and responsive.


the code snipped you show should work wherever you place it, as long as jquery is loaded prior to it.


i cannot imagine any good reason when to have javascript inside of the views. its like having inline styles in your html templates.

if there is any, well, it might be a special behavior to tread. 

#3 Vell



  • Members
  • 100 posts
  • LocationWashington, DC

Posted 03 March 2014 - 08:33 PM

Thanks @danielhanke. I didn't see any good reason why I couldn't put this in my assets .js file. I will start doing that from now on. It always felt wrong to do just wanted to make sure there wasn't a case I was overlooking.

Also tagged with one or more of these keywords: rails, javascript

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users