x6iae
x6iae

Reputation: 4164

How to query a polymorphic associated relationship to return data from multiple tables - rails4

I have some tables that are joined through a polymorphic association...

I am trying to find a way to make a single query to return data from multiple of these tables...

My models are as follow:

#profile.rb
class Profile < ActiveRecord::Base
  has_many :user_profiles, dependent: :destroy
  has_many :wizards, through: :user_profiles, source: :user, source_type: "Wizard"
end

#user_profile.rb
class UserProfile < ActiveRecord::Base
  belongs_to :user, polymorphic: true, dependent: :destroy
  belongs_to :profile
end

#wizard.rb
class Wizard < ActiveRecord::Base
  has_one :user_profile, as: :user, dependent: :destroy
  has_one :profile, through: :user_profile
  has_one :wizard_specialization, dependent: :destroy
  has_one :career, through: :wizard_specialization
end

#career.rb
class Career < ActiveRecord::Base
  has_many :wizard_specializations, dependent: :destroy
  has_many :wizards, through: :wizard_specializations
end

How can I write a join( or :includes) query to return the profile of all wizards, as well as their information from the profiles table, and also include their specialization from the careers table through the wizard_specializations?

Thanks in advance.

PS: It will be great if I can exclude fields like created_at & updated_at

Upvotes: 0

Views: 966

Answers (2)

x6iae
x6iae

Reputation: 4164

I'm not sure if Rails has support for direct AR queries with all my setup configurations...

Anyways, I finally resolved to write it with pure SQL and execute with the help of:

ActiveRecord::Base.connection.execute(query)

where query contains my pure SQL statement with the SELECTs and JOINs and WHEREs

Upvotes: 0

Ryenski
Ryenski

Reputation: 9702

You can use ActiveRecord's includes method to eager-load associated data. Combine that with the select method to include or exclude just the columns that you want:

Wizard.includes(:career, :profile).select('wizards.name', 'wizards.etc', 'careers.name', 'careers.etc', 'profiles.*')

Upvotes: 1

Related Questions