【问题标题】:Filter by fields from joined table when using includes使用包含时按联接表中的字段过滤
【发布时间】:2019-05-12 03:02:10
【问题描述】:

我有 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 中的字段?

【问题讨论】:

  • 你的意思是检索那些有month_forecasts的账户?
  • @vishal - 我知道@months = Account.includes(:month_forecasts) 会为我做到这一点。我的问题是,我需要在MonthForecast 上仅存在于其中而不存在于Account 中的字段上应用一些过滤条件。如何在includes 操作之前或期间应用该过滤器?

标签: ruby-on-rails join activerecord rails-activerecord


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-06
    • 2021-03-19
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多