【问题标题】:return results from active record relation many_to_many assocation从 activerecord 关系 many_to_many 关联返回结果
【发布时间】:2021-05-13 10:46:15
【问题描述】:
我目前在templates 和types 之间有一个many_to_many 关联。
我有templates 的活动记录关系。
我想返回所有链接到这些模板的types。
例如,在理想的世界中,我可以做到templates.types。
我试过templates.joins(:types),但是这会返回templates而不是types。
所以我不确定其他方法可以做到这一点。
【问题讨论】:
标签:
ruby
activerecord
many-to-many
【解决方案1】:
在纯 ruby 中,如果没有 DB,你会想要 flat_map
types = templates.flat_map do |template|
template.types
end
types.uniq # probably you only want unique types
这很有效,但在您获得许多模板/类型时效率不高,因为它会触发更多查询并加载比需要更多的对象。
当您拥有 ActiveRecord 时,您可以向 Type 添加一个 scope 或 self 方法(或者,不是我的示例中的 borth)
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(单表继承)的特殊含义。