【问题标题】:Ruby on Rails: error when using unobtrusive JavaScript to update partialRuby on Rails:使用不显眼的 JavaScript 更新部分时出错
【发布时间】:2014-01-02 20:10:15
【问题描述】:

我使用的是 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 传递给部分?

【问题讨论】:

    标签: javascript ruby-on-rails ruby-on-rails-3 unobtrusive-javascript


    【解决方案1】:

    您的第一个问题是 Rails 类 ActionView::Template 和您的 Template 模型类之间存在名称冲突。您可以通过将模型类称为::Template(顶级Ruby 类)来解决这个问题。例如

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

    但这只是进行主键查找的一种方式,使用find 更简单:

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

    更简单的是,如果您已经设置了从TemplateTaskTemplatebelongs_to 关联,您可以直接引用相关对象:

    <% @template = @templatetask.template %>
    

    这可能会让你更进一步,但如果你想让你的部分更可重用,最好避免让它们引用实例变量(例如@template)。相反,partial 应该引用一个本地的 template 变量,您通过 locals 哈希(您已经在这样做)传递到 render 方法。

    【讨论】:

    • 感谢您的回复.. 设法让它工作;)
    猜你喜欢
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    • 2011-03-09
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 2015-04-07
    相关资源
    最近更新 更多