1

我正在使用Rails 3.2.13,並且在創建'child'項目後嘗試更新'summary'部分。Ruby on Rails:使用不顯眼的JavaScript更新部分時出錯

我有一個模板和模板任務,我試圖做的是更新'顯示'視圖,這是一個摘要,指示有多少任務分配給模板的部分。我正在模板任務的create.js.erb中執行此操作。

這裏是_template-summary.html.erb內容:

<div id="template-summary-details"> 
<table class="table table-striped"> 
    <tbody> 
    <tr> 
     <td><span class="fa fa-th-list"></span> No. of tasks</td> 
     <td><%= @template.templatetasks.count %></td> 
    </tr> 
    <tr> 
     <td><span class="fa fa-clock-o"></span> Total task days</td> 
     <td>        
      <%= @template.templatetasks.sum(:days) %> 
     </td> 
    </tr> 
    <tr> 
     <td><span class="fa fa-check-square-o"></span> No. of checklists</td> 
     <td> 
      <%= @template.templatetasks.count(:checklist_id) %> 
     </td> 
    </tr> 
    </tbody> 
</table>         
</div> 

這裏是create.js.erb內容:

<% @template = Template.where("id = ?", @templatetask.template_id?) %> 

$("#template-summary-details").replaceWith("<%= escape_javascript(render partial: "templates/template-summary", locals: {template: @template}) %>"); 

<% if @templatetask.parent_id? %> 
$('#templatetasks'+<%= @templatetask.parent_id %>).prepend('<%= j render(@templatetask) %>'); 
<% else %> 
$('#templatetasks').prepend('<%= j render(@templatetask) %>'); 
<% end %> 

的問題是,我收到以下錯誤:

undefined method `where' for ActionView::Template:Class 

我也嘗試過使用find但是避風港也沒有得到那個工作。

如何在創建模板任務期間將@template傳遞給partial?

回答

2

您的第一個問題是您在Rails類ActionView::Template和您的Template模型類之間發生名稱衝突。您可以通過將模型類稱爲::Template(頂級Ruby類)來解決該問題。例如

<% @template = ::Template.where("id = ?", @templatetask.template_id).first %> 

但是,這僅僅是一個關於做一個主鍵查找的方式是與find簡單輪:

<% @template = ::Template.find(@templatetask.template_id) %> 

更容易,如果你已經建立了一個belongs_to協會從TemplateTaskTemplate你可以直接參考相關對象:

<% @template = @templatetask.template %> 

這可能會讓你有點進一步但如果你想讓你的部分更加可重用,最好避免讓它們引用實例變量(例如@template)。相反,部分應參考本地template變量,通過locals散列(您正在執行此操作)將其傳遞到render方法中。

+0

謝謝你的迴應..設法讓它工作;) –