我有以下表格:
Table1
:name
:resource
Table2
:FK Table1
:FK Other Table
:quantity
和以下序列化器
class Table1 < ActiveModel::Serializer
attributes :id,
:name,
:resource
end
我需要的是序列化器返回其所有属性以及与之有关系的quantity
from Table2
。
任何帮助,将不胜感激。
ActiveModel::Serializer
实际上支持这一点,这是我的例子
class Table1Serializer < ActiveModel::Serializer
attributes :id, :name, :resource
has_one :table_2, serializer: Table2Serializer
end
class Table2Serializer < ActiveModel::Serializer
attributes :id, :quantity
end
因此,您只需指定与它将起作用的相应序列化器的关系,顺便说一句,我使用它Table1Serializer
不是Table1
为了避免与Table1
(model)产生误解
另一个选择是,如果您不想编写Table2Serializer
,则可以使用custom属性,它类似于:
class Table1Serializer < ActiveModel::Serializer
attributes :id, :name, :resource
attributes :table_2
def table_2
object.table_2
end
end
因此,您可以采用两种方式申请,但是对于您提到的关系,我更喜欢第一种选择,因为以后可能会用到Table2Serializer
!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句