Using Rails 3.1, where do you put your “page specific” JavaScript code?

前端 未结 29 1824
一生所求
一生所求 2020-11-22 11:08

To my understanding, all of your JavaScript gets merged into 1 file. Rails does this by default when it adds //= require_tree . to the bottom of your appl

29条回答
  •  盖世英雄少女心
    2020-11-22 11:21

    This has been answered and accepted long ago, but I came up with my own solution based on some of these answers and my experience with Rails 3+.

    The asset pipeline is sweet. Use it.

    First, in your application.js file, remove //= require_tree.

    Then in your application_controller.rb create a helper method:

    helper_method :javascript_include_view_js //Or something similar
    
    def javascript_include_view_js
        if FileTest.exists? "app/assets/javascripts/"+params[:controller]+"/"+params[:action]+".js.erb"
            return ''
        end
    end
    

    Then in your application.html.erb layout file, add your new helper among the existing javascript includes, prefixed with the raw helper:

    
        Your Application
        <%= stylesheet_link_tag "application", :media => "all" %>
        <%= javascript_include_tag "application" %>
        <%= raw javascript_include_view_js %>
    
    

    Voila, now you can easily create view-specific javascript using the same file structure you use everywhere else in rails. Simply stick your files in app/assets/:namespace/:controller/action.js.erb!

    Hope that helps someone else!

提交回复
热议问题