user3186332
user3186332

Reputation: 370

Nested JSON Response in Ruby/Rails

I have the following models:

class Account < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :sites

and

class User < ActiveRecord::Base
  has_many :accounts

and

class Site < ActiveRecord::Base
  has_and_belongs_to_many :accounts

I am trying to return a JSON representation of a Site that lists all the Accounts information and the User information nested inside.

I added as_json to Site to :include => [:accounts] and added the same method to Account to :include => [:user] however I don't seem to get that nested output in my response. I only get Site -> Account where Account contains the user_id.

Upvotes: 1

Views: 616

Answers (1)

AmitA
AmitA

Reputation: 3245

You have a few options:

  1. site.as_json(include: {accounts: {include: :user}}). See more about usage here: http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html

  2. Override serializable_hash method. The downside is that every time you will call to_json it will kick in, and you may want to serialize Site differently each time based on the use case.

  3. Create your own custom method on Site, e.g. my_serialized_site that will return your desired Hash structure. Then you can call site.my_serialized_site.to_json. You would probably want to also create some scope that includes everything you'd like to include, and then call: Site.my_all_inclusive_scope.map{|x| x.my_serialized_site.to_json}

You can also have each object delegate your custom serialization to dependents.

For example:

class Site
  scope :my_all_inclusive_scope, -> { includes(accounts: :user) }

  def my_serialized_site
    {id: self.id, accounts: {accounts.map(&:my_serialized_account)}}
  end
end

class Account
  def my_serialized_account
    {id: self.id, user: {user.my_serialized_user}}
  end
end

class User
  def my_serialized_user
    { id: self.id, name: name }
  end
end
  1. You may want to look at ActiveModel::Serializer here: https://github.com/rails-api/active_model_serializers

  2. Or look at rabl here: https://github.com/nesquena/rabl

Upvotes: 1

Related Questions