【发布时间】: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