Search code examples
ruby-on-railsrubyactiverecordpolymorphic-associations

Rails joins polymorphic model attribute where condition is met


I can't figure out how to make this query work. I'm looking to get all the user ids of addresses who have a user that is an admin.

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

Solution

  • You cannot directly join the addressable relation as the addressable entities could belong to different models. You could try something like this:

    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 can be used to invoke scopes of joined tables. Here, User model would have a scope called admin which would return admin users.