Arjun N Bharadwaj
Arjun N Bharadwaj

Reputation: 28

Confusion with has_many :through

I am completely confused with implementing has_many :through for the dataset I am using. So I have two tables - scheme_master and scheme_detail

scheme_master has these fields - id, scheme_detail_id, primary_scheme_id

scheme_detail has one relevant field - id

Every scheme in scheme_master has a primary scheme which is self referential to the scheme_master table. For instance, scheme 1 is the primary_scheme of schemes 1,2,3.

Relevant codes are as below

scheme_master.rb

class SchemeMaster < ActiveRecord::Base
  has_one :scheme_detail
  has_many :child_schemes, class_name: "SchemeMaster", 
    foreign_key: :primary_scheme_id, primary_key: :id
end

scheme_detail.rb

class SchemeDetail < ActiveRecord::Base
  belongs_to :scheme_master
end

My question is how do I access Scheme Details of all my child schemes?

Currently,

SchemeMaster.find(1).child_schemes

gives me all the child schemes - 1,2,3, but I want an association which would refer to scheme_detail of the child_schemes. Thank you.

Upvotes: 0

Views: 45

Answers (1)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

Firstly, scheme_masters table has scheme_detail_id, so you need to change this association

class SchemeMaster < ActiveRecord::Base
  belongs_to :scheme_detail
end

class SchemeDetail < ActiveRecord::Base
  has_one :scheme_master
end

Now, to fetch all scheme_detail of the child_schemes, do this

scheme_master = SchemeMaster.includes(child_schemes: :scheme_detail).where(id: 1).first

To fetch scheme_detail of child_schemes, you can do, scheme_master.child_schemes.first.scheme_detail.

Hope that helps!

Upvotes: 1

Related Questions