Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding methods in ActiveRecord::QueryMethods

I want to be able to override certain methods in ActiveRecord::QueryMethods for educational and experimental reasons.

Example: User is an ActiveRecord class that includes modules that overwrite the QueryMethod "order":

User.where("last_logged_in_at < ?", 1.year.ago).order("my own kind of arguments here")

However, I can't seem to get things to work. What module should I override? Something in the ARel gem, AR::Relation, or AR::QueryMethods?

like image 576
Ramon Tayag Avatar asked Nov 28 '25 15:11

Ramon Tayag


1 Answers

I think the answer is to track down where the existing Arel order is defined.

module ActiveRecord
  module QueryMethods
    def order(*args)
      relation = clone
      relation.order_values += args.flatten unless args.blank?
      relation
    end
  end
end

A quick test in console verifies change this will work

module ActiveRecord::QueryMethods
  def order(*args)
    relation = clone
    if args.first
      puts "ordering in ascending id"
      relation.order_values += ["id ASC"]
    else
      puts "ordering in descending id"
      relation.order_values += ["id DESC"]
    end
    relation
  end
end

So, you can do something like this.

But my suggestion would be to create a custom my_order which keeps the original order intact, but encapsulates the same logic.

But you can define this straight on active record

class ActiveRecord::Base
  class << self
    def my_order(*args)
      self.order(*my logic for ordering*)
    end
  end
end
like image 108
Matthew Rudy Avatar answered Dec 02 '25 03:12

Matthew Rudy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!