0

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.