Reputation: 1173
I have this code:
@post.to_json(include: {tags: { only: :name} } )
which produces this output:
{ ... "tags": [{"name": "Lorem"}, {"name": "ipsum"}, {"name": "cupcake"}] ... }
When what I want is:
{ ... "tags": ["Lorem", "ipsum", "cupcake"] ... }
Any ideas?
Upvotes: 0
Views: 70
Reputation: 176412
It's simple, write your own serializer rather than trying to hack the to_json
.
class PostWithTagsSerializer
attr_reader :object
def initialize(object)
@object = object
end
def as_json(*)
hash = object.as_json
hash[:tags] = object.tags.pluck(:name)
hash
end
def to_json(*)
as_json.to_json
edn
end
Then simply use
PostWithTagsSerializer.new(@post).to_json
Upvotes: 1