返回活动记录关系many_to_many关联的结果



我当前在templatestypes之间有许多关联。我有一个templates的活动记录关系。我想返回所有链接到这些模板的types

例如,在理想的世界里,我可以做templates.types。我尝试过templates.joins(:types),但是返回的是templates,而不是types

所以我不确定还有什么办法可以做到这一点。

在纯ruby中,如果没有DB,您会想要flat_map

types = templates.flat_map do |template|
template.types
end
types.uniq # probably you only want unique types

这是有效的,但一旦获得了许多模板/类型,效率就不高了,因为它会触发更多的查询,加载更多的对象。

当您有ActiveRecord时,您可以向Type添加scopeself方法(或者,而不是像我的示例中那样同时添加(

class Type < ApplicationRecord
has_many :template_types
has_many :templates, through: :template_types
scope :for_templates, -> (templates) { joins(:template_types).where(template_types: {template: templates}).distinct } # either this or the method below
def self.for_templates(templates)
Type.joins(:template_types).where(template_types: {template: templates}).distinct
end
end

(我假设连接模型是TemplateType(

然后做

templates = Template.some_complicated_query
Type.for_templates(template)

我建议您重命名Type,因为type已经具有ActiveRecord(单表继承(的特殊含义。

最新更新