0

I have a user object and message object where there is user_id in message model. When I do Message.find(1) how can I get user object as part of the json object or what is the correct way to inject? So it would have the whole user object instead of just user_id

I know I can get it from @message.user but not sure what is the correct way of injecting.

2 Answers 2

1

I think you're looking for:

Message.find(1).to_json(:include => :user)
Sign up to request clarification or add additional context in comments.

Comments

1

When you do Message.find(1, :include => :user), the user object associated with the message object also gets loaded. This is called eager loading. Two objects get loaded with one query. You can then build the Json object with that. Read about eager loading!

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.