Rails 4:escape_javascript渲染部分不起作用

时间:2015-11-06 00:26:33

标签: ruby-on-rails twitter-bootstrap ruby-on-rails-4 bootstrap-modal

在我的Rails 4应用中,我尝试将一些视图显示为modals(使用Bootstrap模式),而不是常规的.html.erb视图。

例如,我有一个calendar模型,控制器中有自定义analysis操作:

def analysis
  @calendar = Calendar.find(params[:id])
  respond_to do |format|
    format.js
  end
end

按照this tutorialthat other tutorial中的说明,我正在尝试创建以下文件:

# _dialog.html.erb

<div class="modal fade" id="dialog" tabindex="-1" role="dialog"  aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" 
                data-dismiss="modal" 
                aria-label="Close">
                <span aria-hidden="true">&times;</span></button>
        <h3 class="modal-title"></h3>
      </div>
      <div class="modal-body">
      </div>

    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
# _analysis.html.erb

<p><%= @calendar.name %> Analysis</p>
# analysis.js.erb

// Add the dialog title
$('#dialog h3').html("Calendar Analysis");

// Render calendar analysis
$('.modal-body').html('<%= j render(:partial => 'calendars/analysis') %>');

// Show the dynamic dialog
$('#dialog').modal("show");

// Set focus to the first element
$('#dialog').on('shown.bs.modal', function () {
    $('.first_input').focus()
  })

最后但并非最不重要的是,我使用_heading.html.erb帮助程序和以下链接调用日历show.html.erb视图内呈现的<%= render 'analysis' %>部分模式:

<%= link_to '<i class="glyphicon glyphicon-dashboard"></i>'.html_safe, calendar_analysis_path, :remote => true, 'data-toggle' =>  "modal", 'data-target' => '#modal-window' %>

当我启动应用程序时,我收到以下错误:

undefined method `render' for #<#<Class:0x007fee248d8118>:0x007fee23577ce0>

- - - -

更新:我尝试过不同的渲染方式:

  • As recommended here,我尝试了escape_javascript renderj render
  • As recommended there,我也尝试过render_to_string而非render
  • 根据其他问题的建议,我甚至尝试了使用render(:partial => 'calendars/analysis')(render 'calendars/analysis')调用部分内容的不同方式。

但这些解决方案都没有奏效。

- - - -

我对这个话题做了很多研究,我不得不说现在我很困惑。

虽然上面提到的两个教程都推荐了这种方法,但其他来源including this one指出,你无法在Rails中渲染部分资产。

因此:

  1. 我目前的代码出了什么问题?
  2. 我尝试使用的方法是否有意义,如果没有,我会做什么呢?

1 个答案:

答案 0 :(得分:2)

app/assets下的代码无法调用render。实际上它除了极少数方法外几乎不能调用任何东西。

将其移至app/views/somethings/analysis.js.erb

其中somethings是复数形式的控制器名称,所以只需将其放在_analysis.html.erb附近。

相关问题