gwalshington
gwalshington

Reputation: 1495

How to use js.erb in rails app

I have tried everything I can find to use a js.erb file, because I need to use ruby along with my js.

I know it is not the code, because I have the same thing in application.js, and it works fine.

Model: topics

I've tried adding topics.js.erb to views/topics/ I've tried a partial _index.js.erb, and rendering it - I see it loading, but it is not executing.

In both files, I have :

$(document).ready(function()    {
    console.log('something');
})

Is there something obvious I'm missing here? Thanks!

Upvotes: 1

Views: 1835

Answers (1)

Michał Młoźniak
Michał Młoźniak

Reputation: 5556

Ok, I think I understand your question now. You have some index action in controller, index.html.erb view and index.js.erb and you want to run javascript from index.js.erb after rendering index.html.erb. It won't work, js.erb views are used for something else. To run your javascript code only when index action is rendered you can just put this javascript code inside index.html.erb view. Or you can put this code in your application.js file and add additional conditions, so it will run only for index action.

There is no Rails way solution to this, but you can try something like this:

index.html.erb:

# ... your code here

<script type="text/javascript">
  window.railsView = "controller_name#index";
</script>

application.js:

$(document).ready(function() {
  if (window.railsView == "controller_name#index") {
    console.log("something");
  }
});

Upvotes: 1

Related Questions