如何从方法的结果序列化嵌套属性?
How to serialize a nested attribute from the result of a method?
我有 3 个模型用户、合同和历史。
用户模型:
class User < ApplicationRecord
has_many :histories
has_many :contracts, through: :histories
end
合约型号:
class Contract < ApplicationRecord
has_many :histories
has_many :users, through: :histories
end
历史模型:
class History < ApplicationRecord
belongs_to :user
belongs_to :contract
end
我正在使用 API 应用程序和 Active Model Serializer gem。在 UserSerializer 中,我有一个方法来获取特定的合同集合,如下所示:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email, :authentication_token, :current_contracts
def current_contracts
object.contracts.find_all{ |contract| contract.current_owner == object.id }
end
end
该方法有效,但结果是一组没有历史记录的合同。即使我的合同序列化器中有这个关联:
class ContractSerializer < ActiveModel::Serializer
attributes :id, :blockchain_id, :created_at, :product_name, :product_info, :price, :histories
has_many :histories
end
期望的结果是能够调用 current_contracts
方法,然后能够从该集合中序列化 contract.histories
。
还有其他方法可以解决这个问题吗?
尝试像这样修改 UserSerializer
:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email, :authentication_token
has_many :current_contracts, each_serializer: ContractSerializer
def current_contracts
object.contracts.find_all{ |contract| contract.current_owner == object.id }
end
end
我有 3 个模型用户、合同和历史。
用户模型:
class User < ApplicationRecord
has_many :histories
has_many :contracts, through: :histories
end
合约型号:
class Contract < ApplicationRecord
has_many :histories
has_many :users, through: :histories
end
历史模型:
class History < ApplicationRecord
belongs_to :user
belongs_to :contract
end
我正在使用 API 应用程序和 Active Model Serializer gem。在 UserSerializer 中,我有一个方法来获取特定的合同集合,如下所示:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email, :authentication_token, :current_contracts
def current_contracts
object.contracts.find_all{ |contract| contract.current_owner == object.id }
end
end
该方法有效,但结果是一组没有历史记录的合同。即使我的合同序列化器中有这个关联:
class ContractSerializer < ActiveModel::Serializer
attributes :id, :blockchain_id, :created_at, :product_name, :product_info, :price, :histories
has_many :histories
end
期望的结果是能够调用 current_contracts
方法,然后能够从该集合中序列化 contract.histories
。
还有其他方法可以解决这个问题吗?
尝试像这样修改 UserSerializer
:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email, :authentication_token
has_many :current_contracts, each_serializer: ContractSerializer
def current_contracts
object.contracts.find_all{ |contract| contract.current_owner == object.id }
end
end