首页 > 解决方案 > Ruby on Rails - 结合 #or 和 #joins

问题描述

我正在开发一个 RoR 应用程序,我遇到了以下问题:我有一个模型A,该模型belongs_to最多有另一个模型的两个单独实例B,我想定义一个范围,该范围返回A满足某些条件的所有实例B使用范围的任一实例B。伪代码:

class A < ApplicationRecord
  belongs_to :first,  class_name: "B", dependent: :destroy, optional: true
  belongs_to :second, class_name: "B", dependent: :destroy, optional: true

  # How to properly do this?
  scope :A_scope, lambda { left_outer_joins(:first).merge(B.B_scope).or(left_outer_joins(:second).merge(B.B_scope)) }
end

在哪里:

class B < Application Record
  scope :B_scope, lambda { .. }
end

我尝试了几种变体,但我一直遇到它的问题:运行但不返回我想要的,或者它给出ArgumentError

ArgumentError (Relation passed to #or must be structurally compatible. Incompatible values: [:left_outer_joins])

标签: ruby-on-railsjoinmergeunion

解决方案


推荐阅读