Tomasz Kowalczyk
Tomasz Kowalczyk

Reputation: 1923

Multiply association to_json

I am working on this code:

render json: User.find(params[:id]).to_json(
      :include => 
      {
        :user_quests => { :inlcude => { :quest }, :only => { :id } }, 
        :user_skills 
      },
      :except => 
      { 
        :authentication_token, 
        :email 
      }
  )

It results in a SyntaxError. The only working code I currently have is:

render json: User.find(params[:id]).to_json(
      :include => 
      [
        :user_quests, 
        :user_skills 
      ],
      :except => 
      [ 
        :authentication_token, 
        :email 
      ]
  )

But I need to pass further parameters to only one of the associations to perform a nested include. The other one (:user_skills) should be fetched the same way as in the working code. How do I do that?

Upvotes: 0

Views: 38

Answers (2)

Tomasz Kowalczyk
Tomasz Kowalczyk

Reputation: 1923

Here it is solution which works for me and is compatible with Rails 4:

render json: User.find(params[:id]).as_json(
      include: 
      { 
        user_quests: 
        { 
          include:  
          { 
            quest: 
            {
              only: :_id 
            }
          }
        },
        user_skills:
        {

        }
        },
      except: [:authentication_token, :email]
  )

Upvotes: 0

D-side
D-side

Reputation: 9485

This code results in a syntax error, because you don't use collections properly. An array ([]) is a list of values, whereas a hashmap (or simply hash, {}) requires key-value pairs.

In to_json's context an array of associations:

[
  :user_quests, 
  :user_skills
]

...is roughly equivalent to a hash of associations mapped to empty option hashes:

{
  :user_quests => {}, 
  :user_skills => {}
}

Having performed that transformation, you can selectively add options wherever you like.

Upvotes: 1

Related Questions