如何避免在has_one关联中嵌套在Serializer中?

时间:2015-02-06 05:22:34

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

我有ProfileSerializer:

class ProfileSerializer < ActiveModel::Serializer
  attributes :id, :role, :name
  has_one :company
end

我得到了

{"user": {"id":7,"role":"guest","name":"misa","company":{"id":2,"user_id":7, ...}}

我有机会避免“公司”嵌套并获得这样的JSON:

{"user": {"user_info": {"id":7,"role":"guest","name":"misa"}, "company_info": {"id":2,"user_id":7, ...}}}

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

class ProfileSerializer < ActiveModel::Serializer
  attributes :id, :role, :name, :company_info

  def company_info
    object.company
  end
end