Skip to content

Instantly share code, notes, and snippets.

@RichOrElse
Last active July 4, 2020 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RichOrElse/51c4667d0a2186481b975594b445f54b to your computer and use it in GitHub Desktop.
Save RichOrElse/51c4667d0a2186481b975594b445f54b to your computer and use it in GitHub Desktop.
Active Record extensions
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.inherited(child_class)
super
child_class.const_get('ActiveRecord_Relation').include(RelationMethods)
end
end
module RelationMethods
def at(id)
find_by(primary_key => id)
end
def select(*fields, **aliases)
return super if block_given?
table = from_clause.name ? @table.alias(from_clause.name) : @table
fields = fields.map { |field| (Symbol === field) ? table[field] : field }
fields += aliases.map { |(field, aliased)| table[field].as(aliased) }
super(*fields)
end
end
@RichOrElse
Copy link
Author

RichOrElse commented Jul 2, 2020

Usage:

User.select(:id, username: 'name')

User.at('1')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment