0

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 }} ) 
2
  • Hey, did my answer work for you?
    – davegson
    CommentedFeb 27, 2015 at 10:29
  • @TheChamp going to give it a try tomorrow, i'll let you knowCommentedFeb 27, 2015 at 17:30

3 Answers 3

2

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 
2
  • this doesn't seem to answer my question. you're still returning the patient_profile_id instead of the actually profileCommentedFeb 28, 2015 at 17:45
  • It's easy to deepen the nesting. I updated my answer to get you the real profile.
    – davegson
    CommentedMar 2, 2015 at 8:36
2

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.

    -1

    Check for overriding as_json method

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.