Created
January 15, 2020 09:39
-
-
Save rosylilly/63d46012d9fd3461837fa5904d7ea0d8 to your computer and use it in GitHub Desktop.
Useful application record snippet for rails application
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
# frozen_string_literal: true | |
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
# List all model classes | |
def self.models | |
@models ||= begin | |
models = [] | |
Rails.root.join('app', 'models').glob('**/*.rb') do |path| | |
model = path.relative_path_from(Rails.root.join('app', 'models')).to_s.sub(%r{\.rb$}, '').classify.safe_constantize | |
models.push(model) if model && model < self | |
end | |
models | |
end | |
end | |
# List reflection foreign columns | |
def self.reflection_columns | |
@reflection_columns ||= reflect_on_all_associations(:belongs_to).map(&:foreign_key) | |
end | |
# List actual attribute columns(without association columns) | |
def self.attribute_columns | |
@attribute_columns ||= columns.map(&:name) - reflection_columns | |
end | |
# List reflection classes | |
def self.reflection_classes | |
@reflection_classes ||= reflect_on_all_associations.map { |r| [r.name.to_sym, r.klass] }.to_h | |
end | |
# Translate association column name by model name | |
# ex: | |
# class User | |
# belongs_to :parent, class_name: 'User' | |
# end | |
# | |
# User.human_attribute_name(:name) => en.activerecord.attributes.user.name | |
# User.human_attribute_name(:parent) => en.activerecord.models.user | |
def self.human_attribute_name(attribute, options = {}) | |
model = reflection_classes[attribute.to_sym] | |
return model.model_name.human(options) if model | |
super(attribute, options) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment