0

How can I chain multiple models to be rendered as a JSON object in rails. Currently I have a render statement like

render json: current_user.role.selected_bids.to_json(include: [:project => {include: [:milestones , :skill_category] } ] )

I want to append to this JSON object another model where I get to include a model associated to :milestones. Something like this

render json: current_user.role.selected_bids.to_json
(include: [:project => {include: [:milestones=> {include: [:timetrackers]}, 
:skill_category]}])

but its throwing a syntax error. Is it possible to do this level of nesting or should I make another API call ?

5
  • You could use serialiser to structure the json or a view based solution such as jbuilder. Commented Oct 16, 2017 at 7:00
  • Oh okay, but is it not possible to include an association here itself ? Commented Oct 16, 2017 at 7:02
  • apidock.com/rails/ActiveRecord/Serialization/to_json Check out the last block. "2nd level and higher order associations work as well" Commented Oct 16, 2017 at 7:08
  • @Anton thanks alot mate :) Commented Oct 16, 2017 at 7:11
  • You welcome! :) Commented Oct 16, 2017 at 7:21

1 Answer 1

1

The reason you are getting a syntax error is because you are trying to create a Hash using syntax you would use to create an Array. You can instead do this something like this:

render json: current_user.role.selected_bids.to_json(
  include: [
    project: { 
      include: [  
        {
          milestones: {
            include: [:timetrackers]
          }, 
        },
        :skill_category
      ]
    }
  ]
)
Sign up to request clarification or add additional context in comments.

1 Comment

Notice how I have wrapped the milestones key inside curly braces to indicate its a Hash.

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.