Search code examples
ruby-on-railsjbuilder

How to display attributes of object when using jbuilder?


I want to show an employee, and all of their reports like the following:

{
name :'ceo'
salary: '1000000'
directs:
    {
        name: 'sally',
        salary: '100000'
    },
    {
        name: 'phil',
        salary: '100000'
    }
}

I must have a defect such that I only get everything under directs. Here's the jbuilder code for the show action:

json.extract! @employee, :name, :salary

json.array! @employee.direct_reports do |d|
    json.name d.name
    json.salary d.salary
end

I've tried several iterations of the first part of the code, but I continually see the following on a rest call, for example http://localhost:3000/employees/1.json:

[    
    {
        name: 'sally',
        salary: '100000'
    },
    {
        name: 'phil',
        salary: '100000'
    }
]

Solution

  • Make sure you have respond_to :json inside the respective controller and you have set @employee variable right.

    Also try stopping and starting the rails application.

    Check out this jbuilder snippet:

    json.extract! @employee, :name, :salary
    
    json.directs @employee.direct_reports do |d|
      json.name d.name
      json.salary d.salary
    end