Rails加入满足条件的多态模型属性

Rails joins polymorphic model attribute where condition is met

我不知道如何使这个查询工作。我正在寻找拥有管理员用户的地址的所有用户 ID。

Address
.near([@address.latitude, @address.longitude], 5)
.where(addressable_type: 'User')
.joins(:addressable)
.where('addressable.is_admin = ?', true)
.pluck(:id)

Address.rb

class Address < ApplicationRecord
  belongs_to :addressable, polymorphic: true

User.rb

class User < ApplicationRecord
  has_one :address, :as => :addressable, dependent: :destroy

您不能直接加入 addressable 关系,因为可寻址实体可能属于不同的模型。你可以尝试这样的事情:

Address
  .near([@address.latitude, @address.longitude], 5)
  .where(addressable_type: 'User')
  .joins("INNER JOIN users on users.id = addresses.addressable_id")
  .merge(User.admin)
  .pluck(:id)

.merge 可用于调用连接表的范围。在这里,User 模型将有一个名为 admin 的范围,它将 return 管理员用户。