0

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.

4

2 回答 2

2

使用active_model_serializers,定义一个自定义序列化程序并为每个模型的序列化程序继承它。

假设我们有Bar一个Baz模型。然后我们为每个定义序列化器:

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

这应该{ foo: 6 }在包含这些模型的每个响应中返回。例子:

{ bar: { foo: 6, id: 1, attr_one: "something", attr_two: "something" } }
{ baz: { foo: 6, id: 1, attr_1: "something", attr_2: "something" } }
于 2013-07-24T18:17:11.777 回答
0

您可以拥有布局并设置通用属性。您可以通过解析产量来休息。

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

于 2014-05-06T13:40:49.763 回答