cifuentes
cifuentes

Reputation: 43

ActiveRecord - Display columns from multiple associations

I have a user, user_profile and profile_type models. A user has_many user_profiles, a user_profile belongs_to a user and belongs_to a profile_type and a profile_type has_many user_profiles.

I have been reading on how to get this work but I am having problems figuring this out and any help would be much appreciated.

I know I could do this with SQL with a statement like this (freehand SQL, excuse mistakes), but I want to use ActiveRecord.

Select up.id, u.user_id, pt.connection_type
from user u
join user_profile up
on u.user_id = up.user_id
join profile_type pt
on pt.profile_type_id = up.profile_type_id
where u.username = "test"

I want to return nested user_profile objects for an associated user but I want the user_profile object to contain the profile_type.connection_type instead of the profile_type.profile_id.

Currently, if I do this,

user.user_profiles.all

add then iterate through the nested user_profiles that are returned, this is my output:

{
:id
:user_id
:profile_type_id
}

What I want is:

{
:id
:user_id
:profile_type.connection_type (instead of profile_type.profile_type_id)
}

User Model

class User < ActiveRecord::Base
  has_many :user_profiles, autosave: true
  has_many :account_settings, autosave: true
end

User_Profile Model

class UserProfile < ActiveRecord::Base
    belongs_to  :user
    belongs_to  :profile_type
end

User Profile Type Model

class ProfileType < ActiveRecord::Base
    has_many :user_profiles
end

Upvotes: 0

Views: 120

Answers (2)

cifuentes
cifuentes

Reputation: 43

I was able to figure out how to do this using Grape.

Since the association was already created, I can use Grape entities to expose what I needed out of the associations. It works seamlessly and I hope this helps anyone else who is having a similar problem.

To get what I was looking for, I needed to gather all user_profiles

userprofiles = user.user_profiles.all

Then, I presented this using Grape

present :user_profile_settings, userprofiles, with: API::V1::Entities::UserProfile

And, here is what my entities looked like:

  class UserProfile < Grape::Entity
    expose :profile_type, using: ProfileTypeEntity
  end

  class ProfileTypeEntity < Grape::Entity
    expose :connection_type
  end

Upvotes: 0

Mohamed El Mahallawy
Mohamed El Mahallawy

Reputation: 13842

Try this:

user.account_settings.select("profile_type.*, profile_type.connection_type").all

Upvotes: 0

Related Questions