ActiveModel Serializers更改关联模型参数的输出

时间:2016-03-29 02:52:13

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

这就是Event的序列化程序现在的样子

class EventSerializer < ActiveModel::Serializer
  attributes :name, :venue, :artists
end

我得到的输出是

[{"name":"Dance your ass off",
  "venue":{"id":21,"name":"Speakeasy","address":"Lynwood Ave","zip_code":30312,"created_at":"2016-03-24T18:13:03.032Z","updated_at":"2016-03-24T18:13:03.032Z"},
  "artists":[{"id":41,"name":"DJ Sliink","bio":"jersey club king","created_at":"2016-03-24T18:13:03.067Z","updated_at":"2016-03-24T18:13:03.067Z"},{"id":42,"name":"DJ Spinn","bio":"Teklife's chief spokesperson","created_at":"2016-03-24T18:13:03.072Z","updated_at":"2016-03-24T18:13:03.072Z"}]}]

如何将其更改为仅显示venueartists的名称?

1 个答案:

答案 0 :(得分:1)

您可以为这些必需属性定义自定义方法,如下所示:

class EventSerializer < ActiveModel::Serializer
  attributes :name, :venue, :artists

  def name
     object.name
  end

  def venue
     object.venue.name
  end

  def artists
     object.artists.map(&:name)
  end
end

您可以参考AMS docs获取更多信息。