我有三个相互嵌套的序列化器。像这样:
class PersonSerializer < ActiveModel::Serializer
attributes :id :name
has_many: companies
class Company < ActiveModel::Serializer
has_many :products
class ProductSerializer < ActiveModel::Serializer
has_many :product_items do
unless person.id != object.company.user_id
object.product_items
end
end
end
end
end
我的问题是一行:unless person.id != object.company.user_id
。
人员在这里未定义。如何访问ProductSerializer中的当前person
实例?
答案 0 :(得分:0)
我不确定为什么需要这种结构,但是一般的class
定义声明了一个新的作用域。是否需要从父范围捕获变量,请使用Class#new
闭包代替:
class PersonSerializer < ActiveModel::Serializer
attributes :id :name
has_many: companies
Company = Class.new(ActiveModel::Serializer) do
has_many :products
ProductSerializer = Class.new(ActiveModel::Serializer) do
has_many :product_items do
unless person.id != object.company.user_id
object.product_items
end
end
end
end
end