我在使用ActiveModelSerializer时遇到问题。
模型test.rb:
class Test < ActiveModel::Serializer
attr_accessor :id, :userName, :lista, :test2
def initialize params = {}
@lista = Array.new
@test2 = Array.new
params.each { |key, value| send "#{key}=", value }
end
end
模型test2.rb:
class Test2 < ActiveModel::Serializer
attr_accessor :id, :userName
def initialize params = {}
params.each { |key, value| send "#{key}=", value }
end
end
test_serializer.rb:
class TestSerializer < ActiveModel::Serializer
attributes :id, :userName, :lista
attributes :test2
public
def test2
Test2Serializer.new(object.test2).as_json
end
end
test2_serializer.rb:
class Test2Serializer < ActiveModel::Serializer
attributes :id, :userName
end
我收到一个错误:
NoMethodError (undefined methodread_attribute_for_serialization’ for #Array:0x00007f1bb52da460):
调试代码后,我发现异常来自此行:
object.read_attribute_for_serialization(attr)
在变量对象中是一个数组。我认为应该是对象。所以我试图改变
Test2Serializer.new(object.test2).as_json
oto
json: object.test2, each_serializer: Test2Serializer
或:
object.test2, each_serializer: Test2Serializer
那没有用。谁能帮我吗?