Rails has_many 通过,调用具有特定类别的所有事件

Rails has_many through, calling all events that have a certain category

所以我有事件,每个事件可以有一个或两个类别,它们的模型如下

class Event < ApplicationRecord
  has_many :categorizations, inverse_of: :event
  has_many :categories, through: :categorizations
end

class Categorization < ApplicationRecord
  belongs_to :event
  belongs_to :category
end


class Category < ApplicationRecord
  has_many :categorizations
  has_many :events, through: :categorizations
end

但是我在调​​用具有特定类别的所有事件时遇到问题,起初我认为是

Event.categories.where(name: "special").each do |event|
.
.
.
end

可以解决问题,但是这似乎行不通,我找到了一些解决方案,但它们似乎效率不高。最好的方法是什么?

您必须加入 表格

Event.joins(:categories).where("categories.name = ?", "special")