首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >序列化程序:推荐的使用连接表的方式(has_many到)

序列化程序:推荐的使用连接表的方式(has_many到)
EN

Stack Overflow用户
提问于 2016-04-23 14:56:09
回答 1查看 1.2K关注 0票数 0

当我需要显示我的连接表中包含的信息时,我面临着这样的情况。例如:

代码语言:javascript
复制
# == 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:

代码语言:javascript
复制
{
  "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"
    }]
  }]
}

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

代码语言:javascript
复制
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

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

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

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

EN

回答 1

Stack Overflow用户

发布于 2018-07-25 18:40:14

我不认为你需要放入额外的方法,比如id,first_name,last_name。相反,可以在序列化程序中使用关联来获取前面提到的适当的JSON数据。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36807688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档