yaru
yaru

Reputation: 1310

How to fetch all associated grand children records?

How to tell ActiveRecord to fetch all links from all Canvases that belong to particular AdTemplate? I have created a canvases_links method for it, but maybe ActiveRecord has some association methods that work out of the box?

class AdTemplate < ActiveRecord::Base
    has_many :canvas

    def canvases_links
      canvas.includes(:links).map do |canva|
        canva.links
      end.flatten
    end    
end

class Canva < ActiveRecord::Base
    belongs_to :ad_template
    has_many :links
    has_many :close_areas
end

class Link < ActiveRecord::Base
  belongs_to :canva
end


a = AdTemplate.find(1)
a.canvases_links # works okay
a.active_record_magic_method_links # must return the same data as a.canvases_links method :)

Upvotes: 2

Views: 59

Answers (1)

MurifoX
MurifoX

Reputation: 15089

You can build a relationship like this:

class AdTemplate < ActiveRecord::Base
  has_many :links, through: :canvas

This way, you can call:

a = AdTemplate.find(1)
a.links
# This will build the query joins automatically

Upvotes: 3

Related Questions