Ask A Question

Notifications

You’re not receiving notifications from this thread.

[delegated_type] How to query a collection of entries including the (entryable) sub-entries.

William Cunningham asked in Rails

I need to query a collection of entries based on a range of dates and then sum an attribute of the sub-entry using the delegated_type method. Something like this:

Entry.where(performed_at: DateTime.now.last_month.all_month).includes(:first_sub_entries or entryable).sum(:total)

I've tried different variations without success. I can retrieve a single record.

Entry.last.entryable.total

Here are the related models:

class Entry < ApplicationRecord
  delegated_type :entryable, types: %w[FirstSubEntry SecondSubEntry]

  validates :performed_at, presence: true
end
module Entryable
  extend ActiveSupport::Concern

  included do
    has_one :entry, as: :entryable, touch: true, inverse_of: :entryable
  end
end
class FirstSubEntry < ApplicationRecord
  include Entryable
  validates :total, presence: true
class
class SecondSubEntry < ApplicationRecord
  include Entryable
  validates :metric, presence: true
class
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,796+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.