Sheharose Sheharose - 1 year ago 102
Ruby Question

Rails query related to polymorphic association

I'm trying to find a query through which I can pull the records from the database... Below is the example

class Apple < AR::Base
has_many :bananas
has_many :events, as: :eventable

class Banana < AR::Base
belongs_to :apple
has_many :events, as: :eventable

class Event < AR::Base
belongs_to :eventable, polymorphic: true

Can I write any single query, where I can pull all the events of a specific apple and all the events of the bananas related to that specific apple.

Answer Source

You need to combine the apple events and the apple's bananas' events into one collection. The simple approach, if an array suffices, is to call:

def events_for apple +

If you want the collection to be an ActiveRecord Relation, you could take the following (arel union based) approach:

def events_for apple
  apple_events =
  banana_ids = apple.bananas.pluck(:id)

  banana_events = Event.where(eventable_type: 'Banana', eventable_id: banana_ids ) 

  all_events = Event.from("
            ) union (
        ) #{Event.table_name}