Question: How to modify the response of as_json in ruby on rails?

Question

How to modify the response of as_json in ruby on rails?

Answers 2
Added at 2017-09-06 22:09
Tags
Question

I have a model called Event, which in turn has_one association with EventType

event = Event.last

event.as_json(include: {event_type: {only: :name}}, only: :event_type)

This is giving me output

{ :event_type=> { "name"=>"Chat" } }

But my desired response is

{ :event_type => "Chat" }

How can I achieve this?

Answers to

How to modify the response of as_json in ruby on rails?

nr: #1 dodano: 2017-09-06 22:09

You could create an instance method on event and include it in the serialized response, using the :methods key (see the documentation for as_json).

But you don't want to create an event_type method, because the association has_one has created one for you. Maybe you can do event_method_name? If you must get exactly the response you wanted, it seems something like JBuilder or Active Model Serializers will give you a better control on the output.

nr: #2 dodano: 2017-09-07 18:09

You can do this in event.rb.

def as_json
  options =  {event_type: event_type[:name]}
  super
end

You might also consider creating and calling a new method to avoid overriding the method in case you need the full object elsewhere.

def event_type_as_json
  {event_type: event_type[:name]}.as_json
end
Source Show
◀ Wstecz