简体   繁体   中英

Simplify .to_json array result in Rails 4

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM