Skip to content

Instantly share code, notes, and snippets.

@nthj
Last active August 29, 2015 13:56
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 nthj/8943602 to your computer and use it in GitHub Desktop.
Save nthj/8943602 to your computer and use it in GitHub Desktop.
I feel evil. [Guess namespaced associations automatically.]
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
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
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