1

I am using rails 4. I have a two models- "Company" & "Employees". Company has_many employees. I want to fetch the company and get all the employees in its nested dictionary in API like this,

  {"Company":{"name":"companyName",
             "total_employees":1000000,
             "Employees":[{"name":"xyz"},
                          {"name":"abc"}]}

In company controller I tried

respond_with(Company.for(@current_user.id))

In company model

scope :for, ->(id) do
 Employee.joins(:company).where(:company_id => id).to_a
end

and getting this output

[{"name":"xyz"},{"name":"abc"}]

But I need company's attributes also. Please help.

2
  • 1
    Try Employee.joins(:company).select("companies.*").where(:company_id => id).to_a Commented Jun 16, 2015 at 17:01
  • By doing this, Each employee dictionary is having companie's attributes. Commented Jun 16, 2015 at 17:05

2 Answers 2

1

This is something that you need to handle in the views with a proper response builder.

While acts_as_api suggested by @rob works, Rails starting from v4.0 has built in support for building and sending rich JSON responses using a typical builder style DSL. It is called jbuilder - https://github.com/rails/jbuilder

Just like you have .html.erb views, you define .json.jbuilder views in the same directory and you are all set to create any type of JSON response.

Particular advantage with jbuilder over acts_as_api is the support for partials (similar to erb templates) and also the fact that the response logic will be in a view as opposed to a model.

P.S: I used acts_as_api until Rails added support for jbuilder views in v4.0

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

Comments

1

you should give act_as_api a try (https://github.com/fabrik42/acts_as_api)

with this gem you can define it very easy like:

class Company < ActiveRecord::Base
  acts_as_api

  has_many :employees

  api_accessible :public do |template|
    template.add :name
    template.add :employees
  end
end

and

class Employee < ActiveRecord::Base
  acts_as_api
  belongs_to :company

  api_accessible :public do |template|
    template.add :name
  end
end

and render it in controller:

    companies = Company.includes(:employees).where(id:1).first

    respond_to do |format|
        format.json {render_for_api  :public, json: companies}
    end

result:

{"company":{"name":"companyName","employees":[{"name":"xyz"},{"name":"abc"}]}}

1 Comment

Thank you for your effort and throwing some light on act_as_api.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.