Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8820227
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T05:33:27+00:00 2026-06-14T05:33:27+00:00

How can I define custom getter functions for ActiveRecord objects in Ruby that will

  • 0

How can I define custom getter functions for ActiveRecord objects in Ruby that will perform operations on an array of the ActiveRecord objects?

For example, I would like to return weighted averages on an array of objects. So if I have Loan objects (1,2,3) with fields amount (100, 200, 300) and default_rate (.1, .2, .3), then with the normal ActiveRecord functions Loan.find(1).amount should return 100, Loan.find(2).default_rate should return .2.

But if I had Loan.find(2,3).default_rate, I would like it to return the weighted average of the default rates, which is .26. I know I can do this using SQL select statements but how can I “overload” the ActiveRecord getter to allow be to define a function when I call the getter on an array of Loan objects rather than a single Loan object?

The loan table has fields amount id, amount, and default_rate

class Loan < ActiveRecord::Base
  module Collection
    def default_rate
      sum(:default_rate * :amount) / sum(:amount)
    end
  end
end

class LoanGroup
  has_many :loans, :extend => Loan::Collection
end

#Then I try
obj = LoanGroup.where('id < 10')

This gives me the error that has_many is undefined in LoanGroup

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T05:33:28+00:00Added an answer on June 14, 2026 at 5:33 am

    To avoid polluting Array‘s namespace with methods specific to collections of Loan records, you might make a wrapper for such a collection and call your methods on that.

    Something like:

    class LoanArray < Array
      def initialize(*args)
        find(*args)
      end
    
      def find(*args)
        replace Array.wrap(Loan.find(*args))
        self
      end
    
      def default_rate
        if length == 1
          self[0].default_rate 
        else
          inject(0) {|mem,loan| mem + loan.defualt_rate } / count
        end
      end
    end
    
    # then
    arr = LoanArray.new(2,3).default_rate #=> 0.26
    arr.find(1,2,3).default_rate          #=> 0.2
    arr.length                            #=> 3
    arr.find(1)                           #=> [<Loan id=1>]
    arr.default_rate                      #=> 0.1
    arr.length                            #=> 1
    

    Original answer below: using an association extension

    Use an association extension. This way the method will be the same whether on a loan, or a collection of loans.

    class MyClass
      has_many :loans do
        def default_rate
          sum(:default_rate) / count
        end
      end
    end
    
    obj = MyClass.find(1)
    obj.loans.first.default_rate               #=> 0.1
    obj.loans.default_rate                     #=> 0.2
    obj.loans.where(:id => [2,3]).default_rate #=> 0.26
    

    If you wanted to keep the logic for loans in the Loan class, you could also write the extension there, e.g.:

    class Loan
      module Collection
        def default_rate
          sum(:default_rate) / count
        end
    
        # plus other methods, as needed, e.g.
        def average_amount
          sum(:amount) / count
        end
      end
    end
    
    class MyClass
      has_many :loans, :extend => Loan::Collection
    end
    

    Edit: as @Santosh points out association.find does not return a relation, so it will not work here. You’d have to use where or some other method which returns a relation.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to know if I can define custom assembly attributes. Existing attributes
In XPages we can define a custom error page that shows whenever a runtime
In C++, we can define a custom locale that enables stream object to ignore
In Spring MVC, one can define interceptors that can perform work before and after
How can I define a custom operator - for example equality operator - for
I know I can define new structs in ruby by doing Person = Struct.new(:first_name,
I know that one can define an 'expected' exception in JUnit, doing: @Test(expect=MyException.class) public
In core.php I can define Configure::write('Routing.admin', 'admin'); and /admin/controller/index will work. but if I
In F#, you can define custom operators like let (=~) input pattern = Regex.IsMatch(input,
How can I create submit button, and define custom title on it, together with

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.