使用 include 时按加入的 table 中的字段过滤

Filter by fields from joined table when using includes

我有 2 个这样的模型:

Account - 有 2 列 account_idaccount_name

MonthForecast - 有 3 列 - account_identityreport_key

我在 Account 中定义了 has_many :month_forecasts,在 MonthForecast 中定义了 belongs_to :account

我正在使用这样的包含:

@months = Account.includes(:month_forecasts)

在上述 includes 操作期间,如何将筛选条件应用于仅存在于 MonthForecast 中的字段?

您需要在 where 中包含加入的 table 名称,如下所示(取决于 rails 版本,您可能还需要包含 .references(:month_forecasts)):

Account.includes(:month_forecasts)
       .where(month_forecasts: { field: :value })