如何获取所有相关的大孩子记录?

时间:2016-07-01 12:29:07

标签: ruby-on-rails ruby-on-rails-4 activerecord rails-activerecord

如何告诉ActiveRecord从属于特定links的所有Canvases中获取所有AdTemplate?我为它创建了一个canvases_links方法,但是ActiveRecord可能有一些开箱即用的关联方法吗?

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 :)

1 个答案:

答案 0 :(得分:3)

你可以建立这样的关系:

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

这样,您可以致电:

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