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? Commented Feb 27, 2015 at 10:29
  • @TheChamp going to give it a try tomorrow, i'll let you know Commented Feb 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
Sign up to request clarification or add additional context in comments.

2 Comments

this doesn't seem to answer my question. you're still returning the patient_profile_id instead of the actually profile
It's easy to deepen the nesting. I updated my answer to get you the real profile.
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.

Comments

-1

Check for overriding as_json method

Comments

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.