Skip to content

Instantly share code, notes, and snippets.

@zhandao
Last active November 10, 2023 05:37
Show Gist options
  • Save zhandao/61266162738dc5f2c7353738fce1092a to your computer and use it in GitHub Desktop.
Save zhandao/61266162738dc5f2c7353738fce1092a to your computer and use it in GitHub Desktop.
[Ruby on Rails] Define method inside ActiveRecord result instance

des to be written.

class User < ApplicationRecord
  def self.select_tag = all.select { _1.tags.present? }

  relation_delegate_class(ActiveRecord::Relation).class_eval do
    def select_age = select { _1.age in ..18 }
    def find_loaded_by(**) = find { my_match?(_1, **) }
  end
end

users = User.some_query
users.loaded?    # => true
users.select_age # no SQL sent~
users.select_tag # equivalent to `User.some_query.scoping { User.all }.select { ... }`
users.find_loaded_by(name: "Jay") # no SQL sent~
class Book < ApplicationRecord
  belongs_to :user

  relation_delegate_class(ActiveRecord::Associations::CollectionProxy).class_eval do
    def unread = select(&:unread?)
  end
end

users = User.includes(:books).some_query
user1 = users.first
user1.books.loaded? # => true
user1.books.unread  # no SQL sent~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment