开发者

Overriding methods in ActiveRecord::QueryMethods

开发者 https://www.devze.com 2023-02-23 02:57 出处:网络
I want to be able to override certain methods in ActiveRecord::QueryMethods for educational and experimental reasons.

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?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号