![](/img/trans.png)
[英]Is there a better way to do Unobtrusive JavaScript on Ruby on Rails?
[英]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::Template
和Template
模型類之間的名稱沖突。 您可以通過將模型類稱為::Template
(頂級Ruby類)來解決此問題。 例如
<% @template = ::Template.where("id = ?", @templatetask.template_id).first %>
但這只是進行主鍵查找的一種方式,使用find
可以更簡單:
<% @template = ::Template.find(@templatetask.template_id) %>
更簡單的是,如果您已經設置了從TemplateTask
到Template
的belongs_to
關聯,則可以直接引用相關對象:
<% @template = @templatetask.template %>
這可能會使您更進一步,但是如果您想使@template
變量更可重用,則最好避免讓它們引用實例變量(例如@template
)。 相反,partial應該引用您通過locals
哈希傳遞到render
方法的本地template
變量(您已經在執行此操作)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.