[英]Rails 5.2 partial counter: “undefined local variable or method” error
Per the information box on https://guides.rubyonrails.org/layouts_and_rendering.html#using-partials : 根据https://guides.rubyonrails.org/layouts_and_rendering.html#using-partials上的信息框:
Rails also makes a counter variable available within a partial called by the collection, named after the title of the partial followed by _counter.
Rails还在集合调用的部分中提供了一个计数器变量,该变量以该部分的标题命名,后跟_counter。 For example, when rendering a collection @products the partial _product.html.erb can access the variable product_counter which indexes the number of times it has been rendered within the enclosing view.
例如,当呈现集合@products时,部分_product.html.erb可以访问变量product_counter ,该变量对已在封闭视图中进行呈现的次数进行索引。
However, I am getting and error when referencing the counter in my partial. 但是,我在部分引用计数器时遇到错误。 Here is the parent view:
这是父视图:
<%= render partial: 'comments/comment_template', collection: @post.comments, as: :c %>
Here is the relevant part of _comment_template.html.erb : 这是_comment_template.html.erb的相关部分:
<%= comment_template_counter %>
And here is the error: 这是错误:
undefined local variable or method `comment_template_counter' for #<#<Class: [etc.]
What am I missing? 我想念什么?
I believe the documentation is incorrect. 我认为该文档不正确。 As pointed out by pedroadame at https://coderwall.com/p/t0no0g/render-partial-with-collection-has-hidden-index , when using the :as option, I need to use the name of the variable rather than the name of the partial .
正如pedroadame在https://coderwall.com/p/t0no0g/render-partial-with-collection-has-hidden-index所指出的那样,当使用:as选项时,我需要使用变量的名称而不是部分的名称。
Furthermore, if elsewhere in my app I am only rendering the partial once instead of as a collection, I need to sidestep the (same) error message by checking whether the counter is defined. 此外,如果在我的应用程序中的其他地方,我仅呈现部分局部而不是作为集合,则需要通过检查计数器是否已定义来回避(相同)错误消息。
So in my partial, this now works: 因此,在我的部分内容中,这现在可行:
<%= c_counter if defined? c_counter %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.