Question

in rails 4, I can not figure out how to fetch model and associated models together.

For example, I have a User model which has_many Message

The following code work properly.

@user = User.find 29, include: :messages
@messages = @user.messages

However, when I try to return @user with @messages in json

render :json @user

The returned result does not contain @messages, only the @user data is returned.

One workaround I can do is to construct a hash with

{user: @user, messages: @messages}

But the problem is messages are not nested or associated to user.

Is there a activemodel/activerecord buildin method to render associated data in a easier way?

Was it helpful?

Solution

as always, the documentation on the rails side is pretty bad. what you need to do is call either call to_json with options or override the models to_json method: http://apidock.com/rails/ActiveRecord/Serialization/to_json

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top