ext
ext

Reputation: 2903

Rails 4 render json layout

Is there a way to append data (e.g. {:foo => 6}) for all json responses so codes such as render :json => {..} would become {"foo": 6, ...}?

I tried to create a json layout in app/views/application.json.erb but didn't seem to make a difference.

The code I'm using is often similar to:

respond_to do |format|
  format.html
  format.json { render json: {..} }
end

I kind of got it working when using a json view but it is a bit cumbersome to create a view for each response.

Upvotes: 0

Views: 1766

Answers (2)

Hrishabh Gupta
Hrishabh Gupta

Reputation: 1988

You can have layout and set common attributes. Rest you can take by parsing yield.

https://stackoverflow.com/a/23496109/1123232

Upvotes: 0

James
James

Reputation: 4737

Use active_model_serializers, define a custom serializer and inherit it for the serializers for each of your models.

Say we have a Bar and a Baz model. Then we'd define serializers for each as:

class FooSerializer < ActiveModel::Serializer
  attributes :foo

  def foo
    6
  end
end

class BarSerializer < FooSerializer
  attributes :id, :attr_one, :attr_two
  # ...
end

class BazSerializer < FooSerializer
  attributes :id, :attr_1, :attr_2
  # ...
end

This should return { foo: 6 } in every response containing these models. Examples:

{ bar: { foo: 6, id: 1, attr_one: "something", attr_two: "something" } }
{ baz: { foo: 6, id: 1, attr_1: "something", attr_2: "something" } }

Upvotes: 2

Related Questions