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.
I think you're looking for:
Message.find(1).to_json(:include => :user)
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!
精彩评论