【问题标题】:Rails 5.2 partial counter: "undefined local variable or method" errorRails 5.2 部分计数器:“未定义的局部变量或方法”错误
【发布时间】:2019-03-17 06:10:05
【问题描述】:

根据https://guides.rubyonrails.org/layouts_and_rendering.html#using-partials上的信息框:

Rails 还在一个名为的部分中提供了一个计数器变量 按集合,以部分的标题命名,后跟 _柜台。例如,在渲染集合@products 时,部分 _product.html.erb 可以访问变量 product_counter 它索引它在 封闭视图。

但是,在我的部分中引用计数器时出现错误。这是父视图:

<%= render partial: 'comments/comment_template', collection: @post.comments, as: :c %>

这里是_comment_template.html.erb的相关部分:

<%= comment_template_counter %>

这是错误:

undefined local variable or method `comment_template_counter' for #<#<Class: [etc.]

我错过了什么?

【问题讨论】:

  • 我已将部分内容从“_comment_template.html.erb”重命名为“_comment.html.erb”(并更新了各种参考资料),但错误仍然存​​在。

标签: ruby-on-rails


【解决方案1】:

我认为文档不正确。正如https://coderwall.com/p/t0no0g/render-partial-with-collection-has-hidden-indexpedroadame 所指出的,当使用 :as 选项时,我需要使用 variable 的名称而不是部分的名称。

此外,如果在我的应用程序的其他地方我只呈现部分一次而不是作为一个集合,我需要通过检查是否定义了计数器来回避(相同的)错误消息。

所以在我的部分,这现在有效:

<%= c_counter if defined? c_counter %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 2013-07-28
    • 2012-03-04
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    相关资源
    最近更新 更多