Rails js.erb file cannot find method “render”

后端 未结 3 1408
遥遥无期
遥遥无期 2020-11-27 19:57

I\'ve got the following code in a Javascript ERB file:

$(document).ready(function() {
  $(\"#workout-week\").append(
    <%= escape_javascript(render :par         


        
相关标签:
3条回答
  • 2020-11-27 20:02

    With the new asset pipeline, inside static assets (/app|lib|vendor/assets/) you can use some 'static' helpers (i.e. <%= asset_path "/foo/bar" %>), because you just compile them once (if you're on production i.e.) and not every time you make an http req. Therefore, it makes no sense to use methods like render (or general 'dynamic' stuff) inside a static asset.

    For your particular case, you could use both *.js.erb views (that will 'match' a particular action inside the controller) or javascript rendered directly inside the html.

    0 讨论(0)
  • 2020-11-27 20:05

    You can't use Rails render. But it's possible to still use partials using Erubis::Eruby rendering directly.

    $(document).ready(function() {
        $("#workout-week").append(<%= escape_javascript(
            Erubis::Eruby.new(File.read(File.join(Rails.root, 'app/views',
            '_show_training_period.html.erb'))).result(period: @period)) %>);
    });
    

    Or in Haml

    $(document).ready(function() {
        $("#workout-week").append(<%= escape_javascript(
            Haml::Engine.new(File.read(File.join(Rails.root, 'app/views',
            '_show_training_period.html.haml'))).render(Object.new, period: @period)) %>);
    });
    

    For some reason using ERB breaks the sprocket rendering.
    And the binding way to pass locals variables is too ugly.

    It's a way around, but it's good to remember that using partials inside assets is not recommended. A better way is to place the partial code hidden somewhere in the HTML and use it in your javascripts.

    0 讨论(0)
  • 2020-11-27 20:07

    You're trying to use render from assets. Unfortunately, it isn't possible now, look at this.

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