0

I have a user model with 2 associated models profile and work capabilities. The user has one profile, but many work capabilities for different types of work. I want to list them as a combined json object like the following using jbuilder:

{profile: { first_name: ...,
           last_name: ...,
           ...
           work_capabilities: [ { capability_1: ...,
                                  ...
                                 },
                                ...
                              ]
         }

}

Currently, I can achieve this by explicitly listing all the profile keys and using json.extract!

   json.profile do
     json.extract! @profile, :first_name, ...
     json.work_capabilities @work_capabilities
   end

My question is, can I create the above object without explicitly listing all the profile attributes? I want every attribute in the profile and would prefer not to have to go back and edit the jbuilder file every time I add an attribute.

sakurashinken
  • 3,940
  • 8
  • 34
  • 67

2 Answers2

1

you can achieve this, by doing below for example in your controller

def index
  @profile = User.find(params[:id]).profile
  @capabilities = User.find(params[:id]).capabilities
end

then in your index.json.jbuilder

json.user do
  json.profile do 
    json.first_name @profile.first_name
    json.last_name @profile.first_name
  end
  json.work_capabilities @work_capabilities.each do |work_capability|
    json.capability_1 work_capability.capability_1
    json.capability_2 work_capability.capability_2
    .
    .
    .
  end
end
Ankur Pohekar
  • 129
  • 1
  • 12
  • This does not really answer the question, which was: "My question is, can I create the above object without explicitly listing all the profile attributes?". Here the profile attributes are all explicitly listed. – vijoc Aug 11 '17 at 08:02
  • 1
    you should try json.merge! for profile attribute – Ankur Pohekar Aug 11 '17 at 10:10
0

I think this will solve your problem

json.profile do
  json.array! @profile_object
end
Ankur Pohekar
  • 129
  • 1
  • 12