views:

33

answers:

1

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. Please help. Thanks in advance.

+1  A: 

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
shingara
@shingara the delegation part gives me this error "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter).". Let me try the method part
Rohit
The first way is doing good and solves my problem. But please find some tweaks in the delegation mechanism and edit the answer. :D
Rohit
@shingara use delegate :model3s, :to => :model1 instead of delegate :model3s, :as => :model1. :D works for me
Rohit
You right. I need check the documentation befopre answer sometimes.
shingara