ed1t
ed1t

Reputation: 8699

Json objects built from model in rails 3

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.

Upvotes: 0

Views: 303

Answers (2)

apneadiving
apneadiving

Reputation: 115521

I think you're looking for:

Message.find(1).to_json(:include => :user)

Upvotes: 1

Syed Aslam
Syed Aslam

Reputation: 8807

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!

Upvotes: 1

Related Questions