在 Rails 5 中,如何 return 合并两个范围或将它们合并为一个范围?

In Rails5, how do I return the union of two scopes or combine them into one?

我正在努力 return 在我的 Rails 应用程序中合并两个范围或将它们合并为一个范围。我正在寻找的结果是检索满足任一范围的所有订单:Order.with_buyer_like 或 Order.with_customer_like。那就是我在寻找集合的并集。重要的是,我需要将它们 return 编辑为 ActiveRecord::Relation,而不是数组。否则,我会做

results =  Order.with_buyer_like + Order.with_customer_like

我也尝试过使用 "or" 运算符但出现错误:

Order.with_seller_like('pete').or(Order.with_customer_like('pete'))
ArgumentError: Relation passed to #or must be structurally compatible. Incompatible values: [:joins]

我也试过将示波器合二为一,但我无法让它正常工作。

这是我的设置:

class Company
  has_many :stores
end 

class Store
  belongs_to :company
end

class Order
  belongs_to :buying_store, class_name: 'Store', foreign_key: 'buying_store_id', required: true 
  belongs_to :selling_store, class_name: 'Store', foreign_key: 'selling_store_id', required: true

  scope :with_buyer_like, ->(search_term) { joins(buying_store: [:company], :customer).where(['stores.name LIKE ? OR companies.name LIKE ?', "%#{search_term.gsub(/ /, '_').downcase}%", "%#{search_term.gsub(/ /, '_').downcase}%"]) }

  scope :with_customer_like, ->(search_term) { joins(:customer).where(['first_name LIKE ? OR last_name LIKE ? OR mobile_number LIKE ? OR email LIKE ?', "%#{search_term.gsub(/ /, '_').downcase}%", "%#{search_term.gsub(/ /, '_').downcase}%", "%#{search_term.gsub(/ /, '_').downcase}%", "%#{search_term.gsub(/ /, '_').downcase}%"] ) } 
end

This blog 对您面临的问题有很好的解释。

总而言之,您必须确保 joinsincludesselect(简称要获取的 AR 数据的结构)在两个范围之间保持一致。

只要您确保两个作用域具有相同的联接,就可以使用此语法。

Order.with_seller_like('pete').or(Order.with_customer_like('pete'))

第一步,检查这是否有效(虽然不推荐):

Order.where(id: Order.with_seller_like('pete')).or(Order.where(id: Order.with_customer_like('pete')))

如果您要在输出中查找 Order 数据,我建议您放弃 joins 并使用子查询样式进行查询。