将多态作用域与或组合

时间:2018-11-07 08:40:41

标签: mysql ruby-on-rails activerecord polymorphism

当它们是多态关联时,如何合并两个范围以在一个查询中获得它们的两个结果?我有这个模型:

class Vendor < ApplicationRecord
  has_many :shipping_method_registers, as: :shipper
  has_many :shipping_methods, through: :shipping_method_registers
end

class City < ApplicationRecord
  has_many :shipping_method_registers, as: :shipper
  has_many :shipping_methods, through: :shipping_method_registers
end

class ShippingMethodRegister < ApplicationRecord
  belongs_to :shipping_method
  belongs_to :shipper, polymorphic: true
end

class ShippingMethod < ApplicationRecord
  has_many :shipping_method_registers, dependent: :destroy, autosave: true
  has_many :city_zones, through: :shipping_method_registers, source: :shipper,
                        source_type: "City"
  has_many :vendors, through: :shipping_method_registers, source: :shipper,
                     source_type: "Vendor"
end

我想结合一个供应商和一个城市的运输方式,但结果却截然不同。我尝试过

> vendor.shipping_methods.or(city.shipping_methods)
ArgumentError: Relation passed to #or must be structurally compatible. Incompatible values: [:joins]
from /usr/local/bundle/gems/activerecord-5.2.0/lib/active_record/relation/query_methods.rb:634:in `or!'

还有

> vendor.shipping_methods.merge(city.shipping_methods)

但这仅返回城市的运输方式。我可以将它们合并到Ruby中,但我想在一个查询中完成。

0 个答案:

没有答案