ruby-on-railsmodel-associationsrails-models

Rails long chain model associations


Well, I know how to handle associations from one model (call it ModelA) through the second one (ModelB) to the third one (ModelC). But what if the third one(ModelC) is associated to the fith one(ModelE) trough the 4th (ModelD).

#ModelA 
has_many :model_bs
has_many :model_cs, :trough => :model_bs

#ModelC
has_many :model_ds
has_many :model_es, :trough => model_ds

The question is: how can I get the collection of ModelE records, associated with the specific ModelA record trough that chain?


Solution

  • Calling model_cs on an instance of ModelA will return an array of model_cs. If you then wanted to access all the model_es you would need to iterate over the array of model_cs and append those results to an array or hash.

    array1 = @model_a.model_cs.all
    array2 = []
    array1.each do |x|
      array2 << x.model_es
    end
    

    array2 now contains all the model_es whose ultimate parent is the original model_a.