Sheharose Sheharose - 6 months ago 36
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
end

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

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


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

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
  apple.events + apple.bananas.map(&:events).flatten
end

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 = apple.events
  banana_ids = apple.bananas.pluck(:id)

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

  all_events = Event.from("
        (
            (
              #{apple_events.to_sql}
            ) union (
              #{banana_events.to_sql}
            ) 
        ) #{Event.table_name}
    ").distinct 
  end
end
Comments