ruby 无法使用find_each迭代存储的对象

snz8szmq  于 2023-05-17  发布在  Ruby
关注(0)|答案(1)|浏览(171)

我正在尝试访问每个订单并在此处执行一些更新操作。然而,当试图运行sidekiq对一个字段进行后台更新时,它向我抛出了一个错误,如NoMethodError: undefined methodfind_each' for #Array:0x00000001156a8ae0`。
之前我的代码库就像

def future_orders
    order= customer_branch.ogs.recurrence_children.of_future
end

def update_orders_instruction
    OrderGroup.transaction do
        future_orders.find_each do |og|
          next if og.is_manually_updated
          instruction = [og.customer_branch&.customer.instruction,customer_branch.instruction].compact.join("\n")
          og.delivery_order.update!(instruction: instruction)
        end
    end
  end
end

find_each方法有效
现在我尝试过滤future_order更多,现在我的代码库看起来像

def future_orders
    future_order= customer_branch.ogs.recurrence_children.of_future | customer_branch.ogs.of_future
    future_order.select { |order| ["Done", "InProgress"].include?(order.status) }
  end

  def update_orders_instruction
    OrderGroup.transaction do
        future_orders.find_each do |og|
          next if og.is_manually_updated
          instruction = [og.customer_branch&.customer.instruction,customer_branch.instruction].compact.join("\n")
          og.delivery_order.update!(instruction: instruction)
  
        end
    end
  end
end

它没有更新,sidekiq抛出了上述错误。

7nbnzgx9

7nbnzgx91#

find_eachActiveRecord::Relation上的方法。但是当你在一个集合上调用select时,整个集合将被加载并在内存中过滤,并返回一个Array。数组不支持find_each,相反,你可以使用each来迭代所有元素。
请注意,find_each的好处是它不会一次将所有记录加载到内存中,而是只加载较小的批(默认值为1000)。当您的集合很大时,那么过滤数据库中的记录当然是有意义的。
改变

future_order = customer_branch.ogs.recurrence_children.of_future | customer_branch.ogs.of_future
future_order.select { |order| ["Done", "InProgress"].include?(order.status) }

future_order = 
  customer_branch
    .ogs
    .recurrence_children
    .of_future.where(orders: { status: ['Done', 'InProgress'] }) | 
  customer_branch
    .ogs
    .of_future.where(orders: { status: ['Done', 'InProgress'] })

保留find_each可能对您有用,具体取决于您的数据库模式。where(orders: { status: ['Done', 'InProgress'] })可能是模型中的作用域。

相关问题