Rail ActiveRecord获取所有多对多关系

Rail ActiveRecord获取所有多对多关系,activerecord,ruby-on-rails-5,Activerecord,Ruby On Rails 5,我在这里看过类似的问题,但似乎没有理解它们 我有三个表项目,大小,和项目大小,其中项目有许多大小到项目大小 项目1.rb: class Item < ApplicationRecord has_many :images has_many :category_items has_many :categories, through: :category_items has_many :item_sizes has_many :sizes, through: :item_

我在这里看过类似的问题,但似乎没有理解它们

我有三个表
项目
大小
,和
项目大小
,其中
项目
有许多
大小
项目大小

项目1.rb:

class Item < ApplicationRecord
  has_many :images

  has_many :category_items
  has_many :categories, through: :category_items

  has_many :item_sizes
  has_many :sizes, through: :item_sizes

  has_many :colour_items
  has_many :colours, through: :colour_items
end

我可以用一个合适的查询来代替这个for循环吗?

您可以在一行中完成

result = items.map{|item| item.sizes }.flatten.uniq

我认为您可以加入
项目大小表
并通过项目ID获取大小:

Size.join(:item\u Size)。其中(item\u Size:{item\u id:items.ids})

谢谢,在结尾添加了
.distinct
。也许应该在问题中澄清。
class ItemSize < ApplicationRecord
    belongs_to :item
    belongs_to :size
end
def get_all_sizes(items)
    results = []
    items.each do |item|
      item.sizes.each do |size|
        results << size unless results.include?(size)
      end
    end
    
    results
  end
result = items.map{|item| item.sizes }.flatten.uniq