如何设置一个'has many :through'一个多态关联

How to set a 'has many :through' a polymorphic association

我定义了我的模型如下。我正在尝试使用 has_many 执行 @user.orders。我已经定义了一个方法:orders 来显示我想要的行为。

class Location < ActiveRecord::Base
  belongs_to :locationable, polymorphic: true
  has_many :orders, ->(location) { where(location.locationable_type == 'User') }, class_name: 'Order', foreign_key: :drop_location_id
  # but this does not check for type
  # it produces the SQL: SELECT "orders".* FROM "orders" WHERE "orders"."drop_location_id" = 
end

class Order < ActiveRecord::Base
  # location is polymorphic, so type of location can be merchant/user
  belongs_to :pickup_location, class_name: 'Location'
  belongs_to :drop_location, class_name: 'Location'
end

class User < ActiveRecord::Base
  has_many :locations, as: :locationable

  # TODO: make it a has_many :orders instead
  def orders
    Order.where(drop_location: locations)
  end
end

使用方法感觉不像 rails 方式。此外,我希望它能与 rails_admin.

配合使用

到目前为止,您应该已经收到一条错误消息,指出您不能通过多态关联使用 has_many。如果您考虑一下,这很有意义,您的 ORM (ActiveRecord) 怎么能制定查询,因为连接会很可怕。