【问题标题】:Rails 5 JSON_API serializersRails 5 JSON_API 序列化器
【发布时间】:2018-02-08 12:04:47
【问题描述】:

我有以下型号:

class Team < ApplicationRecord

  # Associations
  has_many :users
  has_and_belongs_to_many :projects
  belongs_to :team_leader, class_name: 'User'
end

我正在使用 active_model_serializers 版本 0.10.6

这是我的序列化程序中的代码:

class TeamSerializer < ActiveModel::Serializer
  attributes :id, :name, :can_delete, :can_edit

  has_many :projects
  has_many :users
  belongs_to :team_leader
end

这是序列化的结果:

{  
 "data":[  
    {  
       "id":"1",
       "type":"teams",
       "attributes":{  
          "name":"OA",
          "can-delete":true,
          "can-edit":true
       },
       "relationships":{  
          "projects":{  
             "data":[  
                {  
                   "id":"2",
                   "type":"projects"
                }
             ]
          },
          "users":{  
             "data":[  
                {  
                   "id":"25",
                   "type":"users"
                }
             ]
          },
          "team-leader":{  
             "data":{  
                "id":"25",
                "type":"team-leaders"
             }
          }
       }
    }
  ]
}

我遇到的问题是 "team_leader" 关系,正如我所期望的那样,它是 "user" 类型,但事实并非如此。它属于 team-leaders 类型,但我没有模型团队负责人,这在我的前端应用程序(这是一个 ember 2.14 应用程序)中造成了混乱。有没有办法只为关系、序列化程序覆盖 type?如果没有,我愿意接受任何建议以解决此问题...

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5 active-model-serializers json-api


    【解决方案1】:

    试试这个:

    class TeamSerializer < ActiveModel::Serializer
      attributes :id, :name, :can_delete, :can_edit
    
      has_many :projects
      has_many :users
    
      attribute :team_leader do
        team_leader = object.team_leader
        UserSerializer.new(team_leader) if team_leader
      end
    end
    

    这当然意味着UserSerializer的存在,但也可能很简单,例如:

    class UserSerializer < ActiveModel::Serializer
      attributes :id, :foo, :bar, :etc
    end
    

    【讨论】:

    • 不工作。根据您的建议,它会将属性添加到团队,但不会添加到团队的关系中(因为它应该在 json-api 响应中).. 谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 2017-05-19
    • 2018-04-12
    相关资源
    最近更新 更多