1

在我的Rails 4應用程序中,我試圖顯示一些視圖爲modals(使用Bootstrap模式),而不是常規的.html.erb視圖。Rails 4:escape_javascript呈現部分不工作

舉例來說,我有一個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. 我嘗試使用的方法是否有意義,如果不是,我該做什麼?
+0

你的'analysis.js.erb'是否存在於'views'目錄下的某處? –

+0

感謝您的評論。 'analysis.js.erb'目前在'app/assets/javascript'下。這會導致問題嗎? –

回答

1

app/assets下的代碼不能撥打render。事實上,除了少數幾種方法之外,它幾乎不能調用任何東西。

移動它某處app/views/somethings/analysis.js.erb

哪裏somethings是你的複數形式控制器的名稱,所以只要把它附近的_analysis.html.erb

+0

你是完全正確的,這就像一個魅力。非常感謝,我真的很困難。 –

+0

歡迎:) –