You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails存储数据时遇NameError:未初始化常量Enumerators::CompactEnumerator

问题:Ruby on Rails中未初始化Enumerators::CompactEnumerator常量错误

我在Ruby on Rails项目中尝试向数据库存储数据,使用的代码如下:

Enumerators::CompactEnumerator.new(
        Enumerators::MapEnumerator.new(events) { |event|
          event_info =
            IssueEventInfo.new(
              github_id: event[:id],
              actor:
                Actor.new(
                  github_login: event[:actor][:login]
                ),
              created_at: Time.parse(event[:createdAt])
            )

执行时出现错误:

NameError (uninitialized constant Enumerators::CompactEnumerator)

我尝试了各种方法仍无法理解问题所在,希望得到帮助。


解决方案

  • Ruby标准库中不存在Enumerators::CompactEnumerator和Enumerators::MapEnumerator这两个类,直接用Ruby集合内置的map和compact方法就能实现需求:
    events.map do |event|
      IssueEventInfo.new(
        github_id: event[:id],
        actor: Actor.new(github_login: event[:actor][:login]),
        created_at: Time.parse(event[:createdAt])
      )
    end.compact
    
  • 功能对应说明:
    • map遍历events集合,对每个元素执行块内逻辑,返回包含处理结果的新数组,替代原代码中MapEnumerator的作用
    • compact自动移除数组中的nil元素,替代原代码中CompactEnumerator的作用
  • 如果需要显式使用枚举器对象,可通过to_enum实现,但直接调用集合方法更简洁:
    events.to_enum(:map) do |event|
      IssueEventInfo.new(
        github_id: event[:id],
        actor: Actor.new(github_login: event[:actor][:login]),
        created_at: Time.parse(event[:createdAt])
      )
    end.to_a.compact
    

内容的提问来源于stack exchange,提问作者Abid Iqbal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:43:29