【问题标题】:Rails 4: escape_javascript render partial not workingRails 4:escape_javascript 渲染部分不起作用
【发布时间】:2015-11-06 00:26:33
【问题描述】:

在我的 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 视图中呈现,带有 &lt;%= render 'analysis' %&gt; 帮助器和以下链接:

<%= 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 hereescape_javascript renderj render 我都试过了。
  • As recommended there,我也试过render_to_string 而不是render
  • 按照其他问题中的建议,我什至尝试了不同的方法来调用部分,都使用 render(:partial =&gt; 'calendars/analysis')(render 'calendars/analysis')

但是这些解决方案都不起作用。

————

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

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

因此:

  1. 我当前的代码有什么问题?
  2. 我尝试使用的方法是否有意义,如果没有,我应该怎么做?

【问题讨论】:

  • 您的analysis.js.erb 是否位于views 目录下?
  • 感谢您的评论。 analysis.js.erb 目前在 app/assets/javascript 之下。这会导致问题吗?

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


【解决方案1】:

app/assets下的代码不能调用render。实际上它除了极少数方法外几乎什么都不能调用。

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

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

【讨论】:

  • 你完全正确,这就像一个魅力。非常感谢,我真的很努力。
猜你喜欢
  • 2014-12-22
  • 1970-01-01
  • 2017-05-07
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
  • 2015-01-09
相关资源
最近更新 更多