user2954587
user2954587

Reputation: 4871

rails render json nested two levels

How can I expand associations more than one level deep? Right now I can expand reviews but am not sure how to also expand the patient_profile_id?

class Review
   belongs_to :patient_profile
end

render json: doctors.to_json(
      :include => {:reviews => {:include => :patient_profile_id }}
)

Upvotes: 0

Views: 2140

Answers (3)

davegson
davegson

Reputation: 8331

I'd highly suggest you check out the jbuilder gem. There's a great railscast that explains it's usage.

Basically, you will have to add a jbuilder file into your views, that gives you allot more control over your json.

For your specific use case you'd use something like this:

doctors/index.json.jbuilder

json.doctors @doctors do |json, doctor|
  json.(doctor, :id, :name)

  json.reviews doctor.reviews do |json, review|
    json.(review, :id, :rating, :patient_profile_id)

    json.patient_profile review.patient_profile do |json, profile|
      json.(profile, :id, :name, ... ) # attributes of the profile
    end
  end
end

Upvotes: 2

Maxim
Maxim

Reputation: 9981

Try to use something like this:

render json: doctors.to_json(
      :include => {:reviews => {:include => :patient_profile  }}
)

Here you can find detail information how to serialize nested objects.

Upvotes: 2

jgburet
jgburet

Reputation: 535

Check for overriding as_json method

Upvotes: -1

Related Questions