我如何计算渲染部分中的循环?

How can I count a loop within a rendered partial?

我有一个 List 模型和一个 ListItem 模型。

在lists/show我有一些代码,然后我调用

=render @list.list_items

在我的 list_items/list_item 部分中,我有一个在条件存在时运行的循环:

-if condition.exists?
   output
-else
   output something else

我想做的是在 if condition.exists? 里面放一个计数器,这样我就可以知道条件存在了多少次。然后,返回 lists/show 视图,我希望能够在页面顶部告诉用户 condition.exists?.count 与总数 @list.list_items.count

我不确定如何在渲染部分的 if 循环内设置计数器。我知道 render @list.list_items 应该创建一个 list_item_counter', but I only want a counter for the times the condition within the rendered partial exists. Is there a way to trick thelist_item_counter` 来实现这样的功能?

我也不确定如何在 lists/show 视图中访问这个条件计数器,因为我需要完成 render @list.list_items,然后将计数器值传回@list不知何故。

非常感谢任何建议,因为我很困惑。

无法使用内置的 Rails 部分迭代器执行您想要的操作,Rails 提供了一个计数器,它会被称为 list_item_counter部分,但每次迭代它总是会增加一次,你不能有条件地增加它。

要执行您想要的操作,您需要创建自己的迭代器,可能是这样的:

- counter = 0
- @list.list_items.each do |item|
  - if condition.exists?
    - partial = "item"
    - counter += 1
  - else
    - partial = "other_partial"
  = render partial: partial, object: item, locals: { counter: counter }

尝试

cnt = 0
-if condition.exists?
   output
   cnt += 1
-else
   output something else

那么 cnt 将成为你的 计数器