Ruby on rails 如何通过多态关联设置“有很多:通过”

Ruby on rails 如何通过多态关联设置“有很多:通过”,ruby-on-rails,activerecord,has-many-through,Ruby On Rails,Activerecord,Has Many Through,我定义了我的模型如下。我正在尝试使用@user.orders做很多事情。我定义了一种方法:命令来显示我想要的行为 class Location < ActiveRecord::Base belongs_to :locationable, polymorphic: true has_many :orders, ->(location) { where(location.locationable_type == 'User') }, class_name: 'Order', fo

我定义了我的模型如下。我正在尝试使用@user.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" = $1
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\u admin很好地配合使用。

到现在为止,您应该已经收到一个错误,指示您不能通过多态关联使用has\u many。如果你仔细想想,这是很有道理的,你的ORM ActiveRecord怎么能制定查询,因为连接会很可怕。

我认为你是对的,使用的方法不是Rails的方式。但同时,在一个“有很多”的陈述中界定范围是我从未见过的,也从未尝试过的。我推荐:对于Rails中活动记录关联的最佳实践设计,可能是“可怕的”,但它是确定性的。我只需要对类型和常用id进行额外检查。就像在我的orders方法中一样:选择orders.*从orders WHERE orders.drop_location_id在SELECT locations.id从locations WHERE locations.locationable_id=$1和locations.locationable_type=$2