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

Ruby子类继承Serializer父类调用attribute方法报未定义错误如何解决

问题根源

你遇到的报错本质是实例方法和类方法的调用作用域不匹配:

  • 你在CommentSerializer类定义的顶层(类作用域)调用attribute,此时调用主体是CommentSerializer类本身,需要调用类方法
  • 但你当前在Serializer中定义的def attribute(key)是实例方法,只有类的实例对象才能调用,类本身找不到这个方法,所以抛出undefined method "attribute" for CommentSerializer:Class错误

修复方案(仅修改serializer.rb文件)

你需要调整两处核心逻辑:

  1. 把attribute改为类方法,同时用类实例变量存储所有声明的需要序列化的属性
  2. 重写serialize方法,不再直接取Struct的所有成员,而是读取之前声明的属性列表取值

修改后的serializer.rb代码如下:

class Serializer
  def initialize(object)
    @obj = object
  end

  def serialize
    # 取当前类声明的序列化属性列表逐个取值
    self.class.serializable_attributes.inject({}) do |hash, member|
      hash[member] = obj[member]
      hash
    end
  end

  # 类方法:声明需要序列化的属性
  def self.attribute(key)
    @serializable_attributes ||= []
    @serializable_attributes << key
  end

  # 类方法:给实例提供属性列表读取入口
  def self.serializable_attributes
    @serializable_attributes ||= []
  end

  private

  def obj
    @obj
  end
end

修改后运行测试,CommentSerializer中声明的两个属性会被类方法收集,序列化时会按需读取对应字段返回,测试用例即可正常通过。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 14:45:07