簡體   English   中英

Ruby on Rails:使用不引人注目的JavaScript更新部分內容時出錯

[英]Ruby on Rails: error when using unobtrusive JavaScript to update partial

我正在使用Rails 3.2.13,並且在創建“子”項后嘗試更新“摘要”部分。

我有一個模板和模板任務,我想做的是更新“顯示”視圖上的局部視圖,該視圖是一個摘要,指示有多少任務分配給了模板。 我正在模板任務的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?

您的第一個問題是Rails類ActionView::TemplateTemplate模型類之間的名稱沖突。 您可以通過將模型類稱為::Template (頂級Ruby類)來解決此問題。 例如

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

但這只是進行主鍵查找的一種方式,使用find可以更簡單:

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

更簡單的是,如果您已經設置了從TemplateTaskTemplatebelongs_to關聯,則可以直接引用相關對象:

<% @template = @templatetask.template %>

這可能會使您更進一步,但是如果您想使@template變量更可重用,則最好避免讓它們引用實例變量(例如@template )。 相反,partial應該引用您通過locals哈希傳遞到render方法的本地template變量(您已經在執行此操作)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM