1

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.

2
  • Are you sure site.as_json(include: {accounts: {include: :user}}) does not work? I tried this on a similar structure and it works for me. Commented Nov 13, 2015 at 23:19
  • This does work. I wasn't nesting the as_json method as you had done.Thanks! Commented Nov 14, 2015 at 1:28

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.