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

n9vozmp4  于 2023-05-17  发布在  Ruby
关注(0)|答案(1)|浏览(79)

我目前在templatestypes之间有一个many_to_many关联。我有一个活动记录关系templates。我想返回所有链接到这些模板的types
例如,在理想情况下,我可以做templates.types。我尝试了templates.joins(:types),但是返回的是templates而不是types
所以我不确定还有什么方法可以做到这一点。

hzbexzde

hzbexzde1#

在纯ruby中,如果没有数据库,你会想要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(单表继承)中已经有了特殊的含义。

相关问题