Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails joins polymorphic association

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

like image 298
benams Avatar asked Aug 19 '14 18:08

benams


People also ask

What is polymorphic association rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.

How is polymorphic association set up in Rails?

The basic structure of a polymorphic association (PA)sets up 2 columns in the comment table. (This is different from a typical one-to-many association, where we'd only need one column that references the id's of the model it belongs to). For a PA, the first column we need to create is for the selected model.

What is a polymorphic join table?

Polymorphic associations are used in cases when there are several one-to-many relationships that you could aggregate because for all the parents, the children are similar. In other words, a polymorphic association allows for a table to have multiple types of parents.

What is polymorphic association Ruby?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.


1 Answers

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]
like image 128
Shai Avatar answered Oct 04 '22 14:10

Shai