Using Activemodel::Serializer in Rails - JSON Data Differs Between JSON and Index Response

Using ActiveModel::Serializer in Rails - JSON data differs between json and index response

You are not using your serializer in the HTML view. Try this:


App.users = new App.Collections.Users(<%= UserSerializer.new(@users).to_json.html_safe %>);

The reason for this is that the serializer is picked up in the respond_with method, the serializer does not overwrite your .to_json method.

JSON rendering with activemodel serializer in Rails

Product Controller

def index
render json: Product.all, each_serializer: ProductsSerializer, root: false
end

Product Serializer - app/serializers/products_serializer.rb

class ProductsSerializer < ActiveModel::Serializer
attributes :id, :title

end

ActiveModel::Serializer in Rails - serializer methods ignored in JSON result

in the attributes list, you should specify test_id as well

attributes :id, :test_id

Rails Active model serializer returns array instead of json

(Answer from comments)

To use the JSON API adapter, you need to declare you want to use it.

 ActiveModelSerializers.config.adapter = ActiveModelSerializers::Adapter::JsonApi

As per the AMS readme.

Rails ActiveModel::Serializer nest response in data: parent

First off unless you need to support a legacy API use the JSON:API adapter:

By default ActiveModelSerializers will use the Attributes Adapter (no
JSON root). But we strongly advise you to use JsonApi Adapter, which
follows 1.0 of the format specified in jsonapi.org/format.

While nobody fully agrees with all the design decisions in JSON:API it is widely supported by front-end frameworks such as Ember and Angular and is likely to gain further traction.

Otherwise you would need to create your own adapter since the JSON adapter does not allow you to set the root key.

# lib/active_model_serializers/adapters/bikeshed_adapter.rb
module ActiveModelSerializers
module Adapters
class BikeshedAdapter < Json
def root
:data
end
end
end
end

ActiveModelSerializers.config.adapter = :bikeshed

How to implement multiple different serializers for same model using ActiveModel::Serializers?

To avoid mixing view concerns into your models (via serialized variations), use the view to render your JSON for each action, much like we do for HTML.

jbuilder & rabl both fill this data templating need quite nicely.

Update 2013-12-16: The ActiveModelSerializers library does support defining multiple serializers for one model, as @phaedryx answered later, by using custom serializers.



Related Topics



Leave a reply



Submit