【问题标题】:How to set a 'has many :through' a polymorphic association如何设置“有很多:通过”多态关联
【发布时间】:2015-07-03 16:39:20
【问题描述】:

我的模型定义如下。我正在尝试使用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" = $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_admin 很好地配合使用。

【问题讨论】:

  • 我认为你是对的,使用一种方法没有 Rails 方式。但是,在 has_many 语句中确定范围也是我从未见过或尝试过的事情。我推荐:guides.rubyonrails.org/association_basics.html Rails 中 Active Records 关联的最佳实践设计。

标签: ruby-on-rails activerecord has-many-through


【解决方案1】:

现在,您应该已经收到一个错误,指出您不能通过多态关联使用 has_many。如果您考虑一下,这完全有道理,您的 ORM (ActiveRecord) 如何制定查询,因为连接将是可怕的。

【讨论】:

  • '可怕的'也许,但它是确定性的。我只需要额外检查type(以及通常的id)。就像它发生在我的 orders 方法中一样:SELECT "orders".* FROM "orders" WHERE "orders"."drop_location_id" IN (SELECT "locations"."id" FROM "locations" WHERE "locations"."locationable_id" = $1 AND "locations"."locationable_type" = $2)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
  • 2017-09-03
  • 2018-01-28
  • 2012-04-29
  • 1970-01-01
相关资源
最近更新 更多