0

Related to the same question (Loading Javascript per controller in rails)

I want to load a separated javascript file when this controller and one of its views is processed.

So I have some javascript code that works very well, but I want to outsource this code for the controller orders_now. So I paste this code into this file app/assets/javascripts/orders_now.js :

function request_loading_stations ()
{

$.ajax({
    method: "post",
    url: "/orders_now/search_for_loading_stations",

       data: { order_now_post: { loading_station_text_field: $('#loading_station_text_field').val() } }
    })
};

I did also an entry in config/initializers/assets.rb :

Rails.application.config.assets.precompile += %w( orders_now.js )

In the corresponding view I did the following entry to load the orders_now.js file.

<%= javascript_include_tag params[:controller] %>

Then I also restarted the Rails Web Server.


When I reload the Browser Page, the javascript file seems to be not loaded.

In the Browser Developer Tools I can see the javascript file is included:

<script src="/assets/orders_now.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1"></script>

But when I want to check the content of this file I see only:

(function() {


}).call(this);

What's going wrong ?

Community
  • 1
  • 1
Sven Kirsten
  • 478
  • 1
  • 8
  • 27

2 Answers2

0

I've found out that it works when I rename the orders_now.js to any other name, e.g. orders_now_irgendwas.js.

Also the entry Rails.application.config.assets.precompile += %w( orders_now.js ) is not necessary.

And <%= javascript_include_tag params[:controller] %>is also not necessary.

After renaming of orders_now.js the javascript function will always be loaded in the browser on each page request. For now it's ok for me.

Sven Kirsten
  • 478
  • 1
  • 8
  • 27
0

After you've run around the rabbit hole "As I Have"

The lightest approach to this issue is to load your js is via your layouts See (Documents => rails => layouts) Generally these control what is loaded and can be finetuned per action, method, controller

IE: layout false {controller}

class YOURController < ApplicationController
layout "mySpecialOrdersLayoutThatIncludesTheJSRequired", only: [:orders_now]

Or per controller action (method) in orders_now method:

respond_to do |format|
    format.html {render 'mySpecialOrdersLayoutThatIncludesTheJSRequired'}
end

Copy your current layout to mySpecialOrdersLayoutThatIncludesTheJSRequired.html.erb and include the necessary js in this file.

Hope this helps.

pckill
  • 3,709
  • 36
  • 48