Slide 1

Slide 1 text

Reflecting on Active Record Associations @composerinteralia Daniel Colson @dodecadaniel

Slide 2

Slide 2 text

class Repository < ApplicationRecord has_many :pull_requests end class PullRequest < ApplicationRecord belongs_to :repository end

Slide 3

Slide 3 text

• repository • repository=(repository) • build_repository • create_repository • create_repository! • reload_repository • repository_changed? • repository_previously_changed?

Slide 4

Slide 4 text

• repository • repository=(repository) • build_repository • create_repository • create_repository! • reload_repository • repository_changed? • repository_previously_changed? • Presence Validations • Caching • Autosaving • Preloading • Destroy Callbacks • Scopes • Extensions • Etc.

Slide 5

Slide 5 text

Rails Magic !

Slide 6

Slide 6 text

!!!!!!! "#$%&'(

Slide 7

Slide 7 text

Let’s Study Magic!

Slide 8

Slide 8 text

@composerinteralia Daniel Colson @dodecadaniel

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

Study Guide • Metaprogramming • Reflections • Caching • Relations • Inverses

Slide 11

Slide 11 text

Metaprogramming )

Slide 12

Slide 12 text

Metaprogramming class PullRequest < ApplicationRecord belongs_to :repository end

Slide 13

Slide 13 text

Metaprogramming class PullRequest < ApplicationRecord self.belongs_to(:repository) end Calling a class method

Slide 14

Slide 14 text

Metaprogramming class PullRequest < ApplicationRecord def self.belongs_to(name) end end Defining a class method

Slide 15

Slide 15 text

Metaprogramming Reader Method

Slide 16

Slide 16 text

Metaprogramming > pull_request => <#PullRequest @repository_id=42> Reader Method

Slide 17

Slide 17 text

Metaprogramming > pull_request => <#PullRequest @repository_id=42> > pull_request.repository => <#Repository @id=42> Reader Method

Slide 18

Slide 18 text

Metaprogramming > pull_request => <#PullRequest @repository_id=42> > pull_request.repository => <#Repository @id=42> Primary Key Foreign Key Reader Method

Slide 19

Slide 19 text

Metaprogramming def self.belongs_to(name) def repository Repository.where(id: repository_id).first end end Reader Method

Slide 20

Slide 20 text

Metaprogramming Writer Method

Slide 21

Slide 21 text

Metaprogramming > pull_request => <#PullRequest @repository_id=42> Writer Method

Slide 22

Slide 22 text

Metaprogramming > pull_request => <#PullRequest @repository_id=42> > repository => <#Repository @id=77> Writer Method

Slide 23

Slide 23 text

Metaprogramming > pull_request => <#PullRequest @repository_id=42> > repository => <#Repository @id=77> > pull_request.repository = repository => <#PullRequest @repository_id=77> Writer Method

Slide 24

Slide 24 text

Metaprogramming def self.belongs_to(name) def repository Repository.where(id: repository_id).first end def repository=(repository) self.repository_id = repository.id end end Writer Method

Slide 25

Slide 25 text

Metaprogramming def self.belongs_to(name) def repository Repository.where(id: repository_id).first end def repository=(record) self.repository_id = repository.id end end Hardcoded Hardcoded

Slide 26

Slide 26 text

Metaprogramming def self.belongs_to(name) define_method(name) do Repository.where(id: repository_id).first end define_method("#{name}=") do |record| self.repository_id = repository.id end end Generic Generic

Slide 27

Slide 27 text

Metaprogramming def self.belongs_to(name) define_method(name) do Repository.where(:id => self[:repository_id]).first end define_method("#{name}=") do |record| self[:repository_id] = record[:id] end end Hardcoded

Slide 28

Slide 28 text

def self.belongs_to(name) define_method(name) do klass.where(primary_key => self[foreign_key]).first end define_method("#{name}=") do |record| self[foreign_key] = record[primary_key] end end Metaprogramming Generic

Slide 29

Slide 29 text

Metaprogramming class PullRequest < ApplicationRecord belongs_to :repository end

Slide 30

Slide 30 text

Metaprogramming class PullRequest < ApplicationRecord belongs_to :repository end klass => Repository primary_key => :id foreign_key => :repository_id ?

Slide 31

Slide 31 text

Reflections *

Slide 32

Slide 32 text

Reflections class Reflection def initialize(name, active_record) @active_record = active_record @name = name end end

Slide 33

Slide 33 text

Reflections Reflection @active_record = PullRequest @name = :repository

Slide 34

Slide 34 text

Reflections • #klass • #primary_key • #foreign_key Reflection @active_record = PullRequest @name = :repository

Slide 35

Slide 35 text

Reflection @active_record = PullRequest @name = :repository Reflections • #klass => Repository • #primary_key • #foreign_key

Slide 36

Slide 36 text

Reflection @active_record = PullRequest @name = :repository Reflections • #klass => Repository • #primary_key • #foreign_key

Slide 37

Slide 37 text

Reflections class Reflection def klass @name.to_s.camelize.constantize end end

Slide 38

Slide 38 text

Reflections • #klass => Repository • #primary_key => :id • #foreign_key Reflection @active_record = PullRequest @name = :repository

Slide 39

Slide 39 text

Reflections class Reflection def primary_key klass.primary_key end end

Slide 40

Slide 40 text

Reflection @active_record = PullRequest @name = :repository Reflections • #klass => Repository • #primary_key => :id • #foreign_key => :repository_id

Slide 41

Slide 41 text

Reflection @active_record = PullRequest @name = :repository Reflections • #klass => Repository • #primary_key => :id • #foreign_key => :repository_id

Slide 42

Slide 42 text

Reflections class Reflection def foreign_key "#{@name}_id" end end

Slide 43

Slide 43 text

Reflections def self.belongs_to(name) reflection = Reflection.new(name, self)

Slide 44

Slide 44 text

Reflections def self.belongs_to(name) reflection = Reflection.new(name, self) klass = reflection.klass primary_key = reflection.primary_key foreign_key = reflection.foreign_key

Slide 45

Slide 45 text

def self.belongs_to(name) define_method(name) do klass.where(primary_key => self[foreign_key]).first end define_method("#{name}=") do |record| self[foreign_key] = record[primary_key] end end Reflections

Slide 46

Slide 46 text

Caching +

Slide 47

Slide 47 text

Caching > repo = pull_request.repository => # > same_repo = pull_request.repository => #

Slide 48

Slide 48 text

Caching > repo = pull_request.repository => # > same_repo = pull_request.repository => # Different objects

Slide 49

Slide 49 text

Caching > repo = pull_request.repository => # > same_repo = pull_request.repository => # > repo.name = "new_name" > same_repo.name => "old_name" Different objects

Slide 50

Slide 50 text

Caching > repo = pull_request.repository => # > same_repo = pull_request.repository => # > repo.name = "new_name" > same_repo.name => "old_name" Different objects Inconsistent data ,

Slide 51

Slide 51 text

Caching class Association def initialize(owner, reflection) @owner = owner @reflection = reflection @loaded = false @target = nil end end

Slide 52

Slide 52 text

Caching def self.belongs_to(name) define_method(name) do klass.where(primary_key => self[foreign_key]).first end define_method("#{name}=") do |record| self[foreign_key] = record[primary_key] end end

Slide 53

Slide 53 text

Caching def self.belongs_to(name) define_method(name) do end define_method("#{name}=") do |record| end end

Slide 54

Slide 54 text

Caching class Association def reader end def writer(record) end end Association Reader Association Writer

Slide 55

Slide 55 text

Caching class Association def reader klass.where(primary_key => @owner[foreign_key]).first end def writer(record) @owner[foreign_key] = record[primary_key] end end Association Reader Association Writer

Slide 56

Slide 56 text

Caching def self.belongs_to(name) define_method(name) do association(name).reader end define_method("#{name}=") do |record| association(name).writer(record) end end Use Association Reader and Writer

Slide 57

Slide 57 text

Caching def self.belongs_to(name) define_method(name) do association(name).reader end define_method("#{name}=") do |record| association(name).writer(record) end end Use Association Reader and Writer Get Association by name

Slide 58

Slide 58 text

Caching Association @owner = # @reflection = # @loaded = false @target = nil

Slide 59

Slide 59 text

Caching def reader if loaded? else end end Association @owner = # @reflection = # @loaded = false @target = nil

Slide 60

Slide 60 text

Caching def reader if loaded? else end end Association @owner = # @reflection = # @loaded = false @target = nil

Slide 61

Slide 61 text

Association @owner = # @reflection = # @loaded = false @target = nil Caching def reader if loaded? else self.target = klass.where(...).first end end

Slide 62

Slide 62 text

Association @owner = # @reflection = # @loaded = false @target = nil Caching def reader if loaded? else self.target = klass.where(...).first end end true #

Slide 63

Slide 63 text

Caching def reader if loaded? else self.target = klass.where(...).first end end Association @owner = # @reflection = # @loaded = true @target = #

Slide 64

Slide 64 text

Caching def reader if loaded? target else self.target = klass.where(...).first end end Association @owner = # @reflection = # @loaded = true @target = # Association @owner = # @reflection = # @loaded = true @target = #

Slide 65

Slide 65 text

Caching def writer(record) @owner[foreign_key] = record[primary_key] self.target = record end Update target Beware of a stale cache!

Slide 66

Slide 66 text

Caching > repo = pull_request.repository => # > same_repo = pull_request.repository => #

Slide 67

Slide 67 text

Caching > repo = pull_request.repository => # > same_repo = pull_request.repository => # Same object

Slide 68

Slide 68 text

Caching > repo = pull_request.repository => # > same_repo = pull_request.repository => # > repo.name = "new_name" > same_repo.name => "new_name" Same object

Slide 69

Slide 69 text

Caching > repo = pull_request.repository => # > same_repo = pull_request.repository => # > repo.name = "new_name" > same_repo.name => "new_name" Same object Consistent data -

Slide 70

Slide 70 text

Relations .

Slide 71

Slide 71 text

Relations class Repository < ApplicationRecord has_many :pull_requests end

Slide 72

Slide 72 text

def self.has_many(name) define_method(name) do association(name).reader end define_method("#{name}=") do |record| association(name).writer(record) end end Relations

Slide 73

Slide 73 text

Relations class BelongsToAssociation < Association end class HasManyAssociation < Association end

Slide 74

Slide 74 text

def reader if loaded? target else self.target = klass.where(primary_key => @owner[foreign_key]).first end end Relations BelongsToAssociation#reader

Slide 75

Slide 75 text

def reader if loaded? target else self.target = klass.where(primary_key => @owner[foreign_key]).first end end Relations BelongsToAssociation#reader Primary Key Foreign Key

Slide 76

Slide 76 text

def reader if loaded? target else self.target = klass.where(primary_key => @owner[foreign_key]).first end end Relations BelongsToAssociation#reader Primary Key Foreign Key Single Record

Slide 77

Slide 77 text

def reader if loaded? target else self.target = klass.where(foreign_key => @owner[primary_key]).to_a end end Relations HasManyAssociation#reader

Slide 78

Slide 78 text

def reader if loaded? target else self.target = klass.where(foreign_key => @owner[primary_key]).to_a end end Relations Foreign Key Primary Key HasManyAssociation#reader

Slide 79

Slide 79 text

def reader if loaded? target else self.target = klass.where(foreign_key => @owner[primary_key]).to_a end end Relations Foreign Key Primary Key Array of Records HasManyAssociation#reader

Slide 80

Slide 80 text

Relations > repository.pull_requests => SELECT * FROM pull_requests WHERE repository_id = 42 => [#]

Slide 81

Slide 81 text

Relations > repository.pull_requests => SELECT * FROM pull_requests WHERE repository_id = 42 => [#] > repository.pull_requests => [#]

Slide 82

Slide 82 text

Relations What is a Relation?

Slide 83

Slide 83 text

Relations > pull_requests = PullRequest.where(repository_id: 42) => <#ActiveRecord::Relation> What is a Relation?

Slide 84

Slide 84 text

Relations > pull_requests = PullRequest.where(repository_id: 42) => <#ActiveRecord::Relation> • Super-powered array of records • Lazy loading • #create • And much more What is a Relation?

Slide 85

Slide 85 text

Relations > pull_requests = repository.pull_requests => <#ActiveRecord::Relation> Association Relations?

Slide 86

Slide 86 text

Relations > pull_requests = repository.pull_requests => <#ActiveRecord::Relation> Association @loaded = false @target = nil Association Relations?

Slide 87

Slide 87 text

Relations > pull_requests = repository.pull_requests => <#ActiveRecord::Relation> > pull_requests.to_a Association @loaded = false @target = nil Association Relations?

Slide 88

Slide 88 text

Relations > pull_requests = repository.pull_requests => <#ActiveRecord::Relation> > pull_requests.to_a Association @loaded = false @target = nil true [<#PullRequest>] => [<#PullRequest>] Association Relations?

Slide 89

Slide 89 text

Relations class CollectionProxy < ActiveRecord::Relation def initialize(association) @association = association super end end

Slide 90

Slide 90 text

def reader CollectionProxy.new(self) end Relations Updated Reader HasManyAssociation#reader

Slide 91

Slide 91 text

def load_target if loaded? target else self.target = klass.where(foreign_key => @owner[primary_key]).to_a end end Relations HasManyAssociation#load_target Moved From Reader

Slide 92

Slide 92 text

HasManyAssociation @loaded = false @target = nil repository.pull_requests CollectionProxy @association = Relations

Slide 93

Slide 93 text

HasManyAssociation @loaded = false @target = nil repository.pull_requests repository.pull_requests.to_a CollectionProxy @association = Relations

Slide 94

Slide 94 text

HasManyAssociation @loaded = false @target = nil repository.pull_requests repository.pull_requests.to_a CollectionProxy @association = true [] => [] Relations

Slide 95

Slide 95 text

repository.pull_requests repository.pull_requests.to_a => [] repository.pull_requests.create HasManyAssociation @loaded = true @target = [] Relations CollectionProxy @association =

Slide 96

Slide 96 text

repository.pull_requests repository.pull_requests.to_a => [] repository.pull_requests.create HasManyAssociation @loaded = true @target = [] Relations CollectionProxy @association = [#] => #

Slide 97

Slide 97 text

repository.pull_requests repository.pull_requests.to_a => [] repository.pull_requests.create repository.pull_requests.to_a => [#] HasManyAssociation @loaded = true @target = [] Relations CollectionProxy @association = [#] => #

Slide 98

Slide 98 text

Inverses /

Slide 99

Slide 99 text

Inverses class Repository < ApplicationRecord has_many :pull_requests end class PullRequest < ApplicationRecord belongs_to :repository end

Slide 100

Slide 100 text

Inverses > pull_requests = repository.pull_requests => SELECT * FROM pull_requests WHERE repository_id = 42

Slide 101

Slide 101 text

Inverses > pull_requests = repository.pull_requests => SELECT * FROM pull_requests WHERE repository_id = 42 > pull_requests.map(&:repository)

Slide 102

Slide 102 text

Inverses > pull_requests = repository.pull_requests => SELECT * FROM pull_requests WHERE repository_id = 42 > pull_requests.map(&:repository) => SELECT * FROM repositories WHERE id = 42 LIMIT 1 => SELECT * FROM repositories WHERE id = 42 LIMIT 1 => SELECT * FROM repositories WHERE id = 42 LIMIT 1 => SELECT * FROM repositories WHERE id = 42 LIMIT 1 => SELECT * FROM repositories WHERE id = 42 LIMIT 1 0

Slide 103

Slide 103 text

BelongsToAssociation @owner = # @loaded = false @target = nil Inverses

Slide 104

Slide 104 text

BelongsToAssociation @owner = # @loaded = false @target = nil pull_request.repository Inverses

Slide 105

Slide 105 text

BelongsToAssociation @owner = # @loaded = false @target = nil pull_request.repository Inverses HasManyAssociation @owner = # @loaded = true @target = [#, ...] repository.pull_requests

Slide 106

Slide 106 text

BelongsToAssociation @owner = # @loaded = false @target = nil pull_request.repository Inverses true # HasManyAssociation @owner = # @loaded = true @target = [#, ...] repository.pull_requests

Slide 107

Slide 107 text

Inverses HasManyAssociation @owner = # @loaded = true @target = [#, ...]

Slide 108

Slide 108 text

Inverses @target.each do |record| HasManyAssociation @owner = # @loaded = true @target = [#, ...]

Slide 109

Slide 109 text

Inverses @target.each do |record| # HasManyAssociation @owner = # @loaded = true @target = [#, ...]

Slide 110

Slide 110 text

Inverses @target.each do |record| association = record.association(:repository) # HasManyAssociation @owner = # @loaded = true @target = [#, ...]

Slide 111

Slide 111 text

Inverses @target.each do |record| association = record.association(:repository) association.target = @owner # HasManyAssociation @owner = # @loaded = true @target = [#, ...]

Slide 112

Slide 112 text

Inverses @target.each do |record| association = record.association(:repository) association.target = @owner # # HasManyAssociation @owner = # @loaded = true @target = [#, ...]

Slide 113

Slide 113 text

Inverses @target.each do |record| association = record.association(:repository) association.target = @owner end Harcoded

Slide 114

Slide 114 text

Reflection @active_record = Repository @name = :pull_requests Inverses

Slide 115

Slide 115 text

#inverse_name => :repository Reflection @active_record = Repository @name = :pull_requests Inverses

Slide 116

Slide 116 text

#inverse_name => :repository Reflection @active_record = Repository @name = :pull_requests Inverses

Slide 117

Slide 117 text

Inverses class Reflection def inverse_name @active_record.name.underscore end end

Slide 118

Slide 118 text

Inverses @target.each do |record| association = record.association(:repository) association.target = @owner end Harcoded

Slide 119

Slide 119 text

Inverses @target.each do |record| association = record.association(:repository) association.target = @owner end Harcoded @reflection.inverse_name) Generic

Slide 120

Slide 120 text

Inverses > pull_requests = repository.pull_requests => SELECT * FROM pull_requests WHERE repository_id = 42

Slide 121

Slide 121 text

Inverses > pull_requests = repository.pull_requests => SELECT * FROM pull_requests WHERE repository_id = 42 > pull_requests.map(&:repository)

Slide 122

Slide 122 text

Inverses > pull_requests = repository.pull_requests => SELECT * FROM pull_requests WHERE repository_id = 42 > pull_requests.map(&:repository) 1

Slide 123

Slide 123 text

2

Slide 124

Slide 124 text

Further Studies • Through Associations, Polymorphic Associations, Scoping, Etc. • github.com/rails/rails • activerecord/lib/active_record/associations.rb • activerecord/lib/active_record/reflection.rb • activerecord/lib/active_record/associations/* • danieljamescolson.com/blog

Slide 125

Slide 125 text

Practical Applications • Use Rails features • Write less custom code • Write more efficient code • Avoid inconsistent data • Code with confidence

Slide 126

Slide 126 text

Reflecting on Active Record Associations @composerinteralia Daniel Colson @dodecadaniel