如何在.js.erb文件中执行模式的js渲染?

时间:2014-11-21 22:44:29

标签: javascript jquery ruby-on-rails ruby-on-rails-4

我的main.js.erb看起来像这样:

$(document).on("page:change", function(){
  MainJS.init();
    $("#add-video-step-1").html("<%= escape_javascript(render 'videos/upload_video') %>");
    $('#myModalLabel').modal(show);
    Ladda.bind('#video-submit');
    console.log("Upload.js.erb has been executed");

});

基本上我想要发生的是每当按下一个标识为#video-submit的按钮时,我希望它执行部分videos/upload_video中的模态。

只是做一个普通的render 'videos/upload_video'我认为应该足够了,但是当我尝试这个时我得到了这个错误:

NoMethodError at /
undefined method `render' for #<#<Class:0x007f916fcf1310>:0x007f91721a9c20>
  (in /app/assets/javascripts/main.js.erb)

在这一行:

$("#myVCModal").html("<%= escape_javascript(render 'videos/upload_video') %>");

思想?

修改1

以下是每个uDAY请求的部分代码 - 即video/_upload_video.html.erb

<div class="bootstrap-styles">
 <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Upload your Video</h3>
    <p><i>Step 2 of 2 - TEST</i></p>
  </div>
  <div class="modal-body">
    <div class="form">
      <%= form_tag @upload_info[:url], :multipart => true do %>
        <div>Step 2 of 2</div>
        <%= hidden_field_tag :token, @upload_info[:token] %>
        <%= file_field_tag :file, title: 'Choose video to upload' %>
        <p class="uploader">
          <button class="btn btn-success ladda-button" data-color="green" data-style="expand-left"><span class="ladda-label">Upload Video</span><span class="ladda-spinner"></span></button>
        </p>
      <% end %>

    </div>
  </div>
  <div class="modal-footer">
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

您收到错误是因为renderviews (ActionView)的一种方法,而您正在资源中尝试使用它。因此,为了使其工作,我们应该做的是初始化ActionView,为此你的main.js.erb应该是这样的:

$(document).on("page:change", function(){
  MainJS.init();
    <% action_view = ActionView::Base.new(Rails.configuration.paths["app/views"].first) %>
    $("#add-video-step-1").html("<%= action_view.escape_javascript(action_view.render 'videos/upload_video') %>");
    $('#myModalLabel').modal(show);
    Ladda.bind('#video-submit');
    console.log("Upload.js.erb has been executed");

});

我刚尝试了它,它对我有用,试一试,知道它是否适合你:)


对于ajax请求和呈现部分内容,您只需向controller action发送ajax请求,即可将以下代码放入相应的视图文件(action.js.erb)中:

$("#add-video-step-1").html("<%= escape_javascript(render 'videos/upload_video') %>");
$('#myModalLabel').modal(show);