Last active
August 29, 2015 14:04
-
-
Save subvertallchris/f3d1f28d0e7e15c866de to your computer and use it in GitHub Desktop.
really simple example of has_many behavior
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
#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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not sure I understand this:
Post.has_many(:comments, from: Student)
You would call
post.comments
and getStudent
objects?