In a Rails 5 application, I'm using Active Model Serializer 0.10.0.rc4
. I want to include a relation in a json hash.
I have this serializer :
class GroupSerializer < ActiveModel::Serializer
attributes :id, :name, :subscription_ids, :nb_places, :description,
:schedule, :course_id
end
And I'm using it like this :
resource = Group.all
ActiveModel::Serializer.serializer_for(resource).new(resource, include: :subscriptions).as_json
And I have this :
{"group"=>{:id=>1, :name=>"12", :subscription_ids=>[1, 2, 3], :nb_places=>12, :description=>nil, :schedule=>"12", :course_id=>1}}
I don't understand why subscriptions are not included. I don't want to use has_many
in the serializer because it cause infinite loop when the there is multiple rules.
I want something like this :
{"group"=>{:id=>1, :name=>"12", :subscription_ids=>[1], :nb_places=>12, :description=>nil, :schedule=>"12", :course_id=>1, :subscriptions=>[{:id=>1,:name=>'something'}]}
What can I do?
You can create a subscriptions method like this:
attributes :subscriptions
def subscriptions
object.subscriptions.as_json(only: [:id, :name])
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.