Last active
August 29, 2015 13:56
-
-
Save nthj/8943602 to your computer and use it in GitHub Desktop.
I feel evil. [Guess namespaced associations automatically.]
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 ActiveRecord::Reflection::AssociationReflection | |
class AmbiguousAssociationClassError < Exception | |
def initialize results | |
super "Could not guess association, please specify using class_name. Likely options: #{results.join(', ')}" | |
end | |
end | |
def klass | |
super | |
rescue NameError | |
@klass ||= ActiveRecord::Base.descendants.select do |model| | |
model.name.demodulize.parameterize('_') == class_name.parameterize('_') | |
end.tap do |results| | |
raise AmbiguousAssociationClassError.new(results) if results.many? | |
end.first | |
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
class Project < ActiveRecord::Base | |
class Attachment < ActiveRecord::Base | |
# Yes, we're smart enough to guess the Project::Discussion class_name | |
belongs_to :discussion | |
end | |
class Discussion < ActiveRecord::Base | |
belongs_to :project | |
has_many :attachments | |
end | |
belongs_to :user | |
has_many :discussions | |
has_many :attachments, | |
through: :discussions | |
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
class User < ActiveRecord::Base | |
has_many :projects | |
has_many :discussions, | |
through: :projects | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment