ActiveModel :: Serializer:与连接表一起使用的推荐方法(has_many through)

时间:2016-04-23 06:56:09

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

我遇到需要显示连接表中包含的信息的情况。例如:

# == Schema Information
#
# Table name: quality_inspections
#
#  id, content
#
# =============================================================================

class QualityInspection
  has_many :inspection_inspectors
  has_many :inspector, through: :inspection_inspectors
end

# == Schema Information
#
# Table name: inspection_inspectors
#
#  quality_inspection_id, inspector_id, inspection_date
#
# =============================================================================

class InspectionInspector
  belongs_to :quality_inspection
  belongs_to :user, foreign_key: :inspector_id
end

然后,我想要以下json:

{
  "quality_inspectors": [{
    "id": 1,
    "content": "foo",
    "inspectors": [{
      "id": 1, // which is the user's id
      "first_name": "Bar",
      "last_name": "FooFoo",
      "inspection_date": "random date"
    }]
  }]
}

现在,我在序列化程序中执行以下操作:

module Api::V1::QualityInspections
  class InspectorSerializer < ActiveModel::Serializer
    type :inspector

    attributes :id, :first_name, :last_name, :inspection_date

    def id
      inspector.try(:public_send, __callee__)
    end

    def first_name
      inspector.try(:public_send, __callee__)
    end

    def last_name
      inspector.try(:public_send, __callee__)
    end

    private

    def inspector
      @inspector ||= object.inspector
    end
  end
end

你有更好的解决方案吗?或者我可能没有在我的Serializer上使用正确的方法?

无论如何,当我在连接表上显示信息时,我真的很困惑。奇怪的是,使用cerebris / jsonapi-resources时我也遇到了同样的问题。

编辑:关于GH的链接问题:https://github.com/rails-api/active_model_serializers/issues/1704

1 个答案:

答案 0 :(得分:0)

我认为您不需要添加其他方法,例如id,first_name,last_name。取而代之的是,在序列化程序中使用关联以获取相应的JSON数据,如前所述。