如何告诉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 :)
答案 0 :(得分:3)
你可以建立这样的关系:
class AdTemplate < ActiveRecord::Base
has_many :links, through: :canvas
这样,您可以致电:
a = AdTemplate.find(1)
a.links
# This will build the query joins automatically