这就是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"}]}]
如何将其更改为仅显示venue
和artists
的名称?
答案 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获取更多信息。