Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a :has_many :through association on a belongs_to association Ruby on Rails

I have three models, each having the following associations:

class Model1 < ActiveRecord::Base
  has_many :model2s
  has_many :model3s
end

class Model2 < ActiveRecord::Base
  belongs_to :model1
  has_many :model3s, :through => :model1  # will this work? is there any way around this?
end

class Model3 < ActiveRecord::Base
  belongs_to :model1
  has_many :model2s, :through => :model1  # will this work? is there any way around this?
end

As you can see in the commented text, I have mentioned what I need.

like image 355
Rohit Avatar asked Feb 04 '23 01:02

Rohit


1 Answers

You just create the method to access it

class Model2 < ActiveRecord::Base
  belongs_to :model1

  def model3s
    model1.model3s
  end
end

Or, you can delegate to model1 the model3s method

class Model2 < ActiveRecord::Base
  belongs_to :model1

  delegate :model3s, :to => :model1

end
like image 185
shingara Avatar answered Feb 05 '23 15:02

shingara