Activemodel::serializer Not Working
Solution 1:
This is not working because your controller isn't actually rendering out using the ActiveModel::Serializer
. You'd need to write it like this:
defnearby_from_category@closest_clients = Client.from_category(params[:category]).
activated.locateable.all_with_translation(@lang).
by_distance(origin: remote_ip).limit(2)
render json:@closest_clientsend
In the event that you want to customize the serializer as indicated by the additional args on your to_json
call, you'd have to modify the ClientSerializer
that already exists to:
classClientSerializer < ActiveModel::Serializer
attributes :id, :name, :path, :url
has_many :translations
has_many :picturesdefurl
client_url(object)
enddefpath
client_path(object)
endendclassTranslationSerializer < ActiveModel::Serializer
attributes :name, :contentendclassPictureSerializer < ActiveModel::Serializer
attributes :imageend
Solution 2:
When using ActiveModel::Serializers (AMS) you should simply use:
render json: @post
The whole point of serializers is to move your json structure out of your controllers. So lets start out by getting rid of the include
hash in the render call:
defnearby_from_category@closest_clients = Client.from_category(params[:category]).
activated.locateable.all_with_translation(@lang).
by_distance(origin: remote_ip).limit(2)
render json:@closest_clientsend
In most cases AMS can figure out which serializer to use for collections by itself by looking at the contents. You can specify it manually with the each_serializer
option.
To include the translations and pictures you would redefine your serializer:
classClientSerializer < ActiveModel::Serializer
attributes :id, :name, :path, :urlhas_many::translationshas_many::picturesdefurl
client_url(object)
enddefpath
client_path(object)
endendclassTranslationSerializer < ActiveModel::Serializer
attributes :name, :contentendclassPictureSerializer < ActiveModel::Serializer
attributes :imageend
One big gotcha is that you may be creating a N + 1 query issue since the associations will be loaded separately for each client unless joined. This is not an AMS specific issue.
The many resulting SQL queries will slow down your server and can cause it to run out of memory. See the rails guides for potential solutions.
Post a Comment for "Activemodel::serializer Not Working"