Last active
July 4, 2020 04:31
-
-
Save RichOrElse/51c4667d0a2186481b975594b445f54b to your computer and use it in GitHub Desktop.
Active Record extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
def self.inherited(child_class) | |
super | |
child_class.const_get('ActiveRecord_Relation').include(RelationMethods) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
User.select(:id, username: 'name')
User.at('1')