rails joins polymorphic association

浪尽此生 提交于 2019-12-10 04:10:08

问题


I have a ploymorphic association named Notifiable in a model named Notifiaction:

module Notifiable
  def self.included(base)
    base.instance_eval do
      has_many :notifications, :as => :notifiable, :inverse_of => :notifiable, :dependent => :destroy
    end
  end
end

class Bill < ActiveRecord::Base
  include Notifiable
end

class Balance < ActiveRecord::Base
  include Notifiable
end

class Notification
  belongs_to :notifiable, :polymorphic => true
  belongs_to :bill, foreign_key: 'notifiable_id', conditions: "notifiable_type = 'Bill'"
  belongs_to :balance, foreign_key: 'notifiable_id', conditions: "notifiable_type = 'Balance'"
end

when I try to join notification with notifiable (Notification.joins{notifiable} - it's squeel, active record code will have the same result) I get the error: ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association :notifiable

I've seen some posts about this exception but none of them was exactly my case when I try to just join the tables. Is it possible? what am I missing


回答1:


You can eager load both polymorphic associations by using includes:

Notification.where(whatever: "condition").includes(:notifiable)

Considering both Bill and Balance results match the query result, the include should preload both models in the query result. ie:

Notification.where(whatever: "condition").includes(:notifiable).map(&:notifiable)
# => [Bill, Balance, etc]



回答2:


Since you already have the bill and balance associations declared, you Can join individual associations and Do a Union on them.

Something like

scope :billiables_for_account, ->(account) do
  union_scope(joins(:bill).where(bills: {account: account}),
      joins(:balance).where(bills: {account: account}))
end


来源:https://stackoverflow.com/questions/25390384/rails-joins-polymorphic-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!