【问题标题】:How to serialize a nested attribute from the result of a method?如何从方法的结果中序列化嵌套属性?
【发布时间】:2018-06-15 01:55:41
【问题描述】:

我有 3 个模型 User、Contract 和 History。

用户模型:

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

我还有其他方法可以解决这个问题吗?

【问题讨论】:

  • find_all 返回一个数组,我猜ActiveModel::Serializer 不喜欢那样。当您在 current_contracts 中返回 object.contracts 时会发生什么?
  • 嗨乔希。我需要那个方法,因为我不需要所有的 user.contracts 我只需要满足方法中条件的合同。

标签: ruby ruby-on-rails-3 active-model-serializers


【解决方案1】:

尝试像这样修改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

【讨论】:

  • 感谢 Aetherus 正是我想要的。
猜你喜欢
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
  • 2019-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多