Skip to content

Instantly share code, notes, and snippets.

@subvertallchris
Last active August 29, 2015 14:04
Show Gist options
  • Save subvertallchris/f3d1f28d0e7e15c866de to your computer and use it in GitHub Desktop.
Save subvertallchris/f3d1f28d0e7e15c866de to your computer and use it in GitHub Desktop.
really simple example of has_many behavior
#copy and paste into rails console to play
module DumbHasMany
extend ActiveSupport::Concern
module ClassMethods
def has_many(method, args=nil)
if args.nil? || !args.is_a?(Hash)
type = method
else
type = initial_type = args.has_key?(:through) ? args[:through].to_s.downcase : method
if args.has_key?(:to) || args.has_key?(:from)
type = args.has_key?(:to) ? "#{self.name}##{initial_type}" : "#{args[:from]}##{initial_type}"
end
end
"method is #{method}, type is #{type}"
end
end
end
class Post
include DumbHasMany
def name
"Post"
end
end
class Student
include DumbHasMany
def name
"Student"
end
end
Post.has_many(:comments, through: :thoughts_about_stuff)
Post.has_many(:comments, from: Student)
a = Student.has_many(:comments, to: Post)
b = Post.has_many(:comments, from: Student)
a == b
a = Student.has_many(:comments, to: Post, through: :thoughts_about_stuff)
b = Post.has_many(:comments, from: Student, through: :thoughts_about_stuff)
a == b
@cheerfulstoic
Copy link

Not sure I understand this:

Post.has_many(:comments, from: Student)

You would call post.comments and get Student objects?

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