简体   繁体   中英

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!

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");
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM