Is there a way to reorganize the unpacking of a polymorphic association into its model?

Example:

Say we have a Reminder model with polymorphic association.

class Reminder < ActiveRecord::Base
  belongs_to :rememberable, polymorphic: true
  scope :events, -> { where(rememberable_type: 'Event') }
end

Then I can get a list of all remembered events with

events = Reminder.events.map(&:rememberable)

Question:

Is there a way to include this extension in a polymorphic association or in the reminder area? So we can call it this:

events = Reminder.events.unpack

What I tried:

I tried

class Reminder < ActiveRecord::Base
  belongs_to :rememberable, polymorphic: true do
    def unpack
      map(&:rememberable)
    end
  end
  scope :events, -> { where(rememberable_type: 'Event') }
end

and

class Reminder < ActiveRecord::Base
  belongs_to :rememberable, polymorphic: true
  scope :events, -> { where(rememberable_type: 'Event') }
  scope :unpack, -> { to_a.map(&:rememberable) }
end

without success.

Sidenote:

I know that a common bad practice is that the scope ends with ActiveRecord proxy connectivity.

+4
source share
2 answers

ActiveRecord map / to_a, Rails.

" " " , ". , . Reminder, Event.

1- :

module Rememberable
  extend ActiveSupport::Concern

  included do |base|
    base.scope :with_reminders, -> { joins :reminders }
  end  
end

2- .

class Event < ActiveRecord::Base
  include Rememberable
  ...

3-

events = Event.with_reminders
+2

. Rails. ( Reminder):

def self.unpack
  @relation.map(&rememberable)
end

:

scope :unpack, -> { @relation.map(&rememberable) }

- , - ActiveRecord, ( ).

+1

All Articles