Search code examples
ruby-on-railsnested-resources

Rails - Include nested resource in model


I know how to include nested resources in controller render like this:

render :json => @user, :include => {:profile}

My doubt is: is it possible to do this in models?

I tried many ways but it doesn't give me the user and his profile like this:

{
    id: 1,
    name: 'John',
    profile: {
        id: 64,
        status: 'active'
    }
}

I tried this in my model:

User.where(id: 1).includes(:profile)

And the output was:

User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
Profile Load (0.2ms)  SELECT `profiles`.* FROM `profiles` WHERE `profiles`.`user_id` IN (1)

Solution

  • Edit: Ignoring render. If you want to include associated models in a JSON output just call [to_json with include as an option][1].

    Edit two: Based up our chat it looks like you're wanting to get to objects, not JSON data.

    Using your example user record:

    users = User.includes(:profile).where("YOUR CONDITIONS") 
    users.each do |user|
      puts user.profile.status #or do something with your loop
    end