Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails belongs_to through via association

I'm on rails 3.0 and trying to figure out what would be the proper way to setup a belong_to :through relationship (which) I know is not possible. Here's an example:

class ParentCompany < ActiveRecord::Base
  has_many :subsidiaries
  has_many :employees, :through => :subsidiaries
end

class Subsidiary < ActiveRecord::Base
  belongs_to :parent_company
  has_many :employees
end

class Employee < ActiveRecord::Base
  belongs_to :subsidiary
  belongs_to :parent_company, :through :subsidiary # <-- I know this is invalid
end

I know I can solve it by doing:

class Employee < ActiveRecord::Base
  def parent_company
    subsidiary.parent_company
  end
end

However, I'd like to know if I can do the above via associations.

like image 537
rforte Avatar asked Nov 22 '25 14:11

rforte


1 Answers

You can use delegate to accomplish this without using an association

class Employee < ActiveRecord::Base
  belongs_to :subsidiary
  delegate :parent_company, to: :subsidiary
end
like image 141
infused Avatar answered Nov 25 '25 09:11

infused



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!