How to include js.erb file in view folder

前端 未结 2 1545
挽巷
挽巷 2021-01-05 06:55

I have a JavaScript file to use with a view. There needs to be Ruby code in it, and I need to do render in Ruby, so I understand that I can\'t put the JavaScrip

相关标签:
2条回答
  • 2021-01-05 07:34

    javascript_include_tag won't work js.erb declared in the view folder itself. There are three different ways you can have the javascript.

    1] Write the code in the view, i.e., in the html.erb itself.

    2] Create js file in public/javascripts folder and include it using javascript_include_tag.

    3] In case you want to make the request as Ajax:

    • Create the js.erb in the view folder itself with the same name as that of the action.
    • In the view where some form is created which will be calling this action, make the request using :remote => true.
    • In the called action, use code as follows:

      def action
        respond_to do |format|
          format.js
        end
      end
      
    0 讨论(0)
  • 2021-01-05 07:45

    you can do this by

    render :partial => "myfile"
    

    you have to keep your file in controller's view directory with name _myfile.js.erb

    Now you can write your own code (js,ruby) here and probably can separate out js with javascript_include_tag to avail asset pipline

    This file will be first rendered by erb engine and then as javascript.

    0 讨论(0)
提交回复
热议问题