Class: Rasti::DB::Relations::ManyToMany
- Inherits:
-
Base
- Object
- Base
- Rasti::DB::Relations::ManyToMany
show all
- Defined in:
- lib/rasti/db/relations.rb
Instance Attribute Summary
Attributes inherited from Base
#name, #source_collection_class
Instance Method Summary
collapse
Methods inherited from Base
#initialize, #many_to_many?, #many_to_one?, #one_to_many?, #target_collection_class
Instance Method Details
#graph_to(rows, db, schema = nil, relations = []) ⇒ Object
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
|
# File 'lib/rasti/db/relations.rb', line 131
def graph_to(rows, db, schema=nil, relations=[])
pks = rows.map { |row| row[source_collection_class.primary_key] }
target_collection = target_collection_class.new db, schema
relation_name = qualified_relation_collection_name schema
join_rows = target_collection.dataset
.join(relation_name, target_foreign_key => target_collection_class.primary_key)
.where(Sequel.qualify(relation_name, source_foreign_key) => pks)
.all
Relations.graph_to join_rows, relations, target_collection_class, db, schema
relation_rows = join_rows.each_with_object(Hash.new { |h,k| h[k] = [] }) do |row, hash|
attributes = row.select { |attr,_| target_collection_class.model.attributes.include? attr }
hash[row[source_foreign_key]] << target_collection_class.model.new(attributes)
end
rows.each do |row|
row[name] = relation_rows.fetch row[target_collection_class.primary_key], []
end
end
|
#qualified_relation_collection_name(schema = nil) ⇒ Object
127
128
129
|
# File 'lib/rasti/db/relations.rb', line 127
def qualified_relation_collection_name(schema=nil)
schema.nil? ? relation_collection_name : Sequel.qualify(schema, relation_collection_name)
end
|
#relation_collection_name ⇒ Object
123
124
125
|
# File 'lib/rasti/db/relations.rb', line 123
def relation_collection_name
@relation_collection_name ||= @options[:relation_collection_name] || [source_collection_class.collection_name, target_collection_class.collection_name].sort.join('_').to_sym
end
|
#source_foreign_key ⇒ Object
115
116
117
|
# File 'lib/rasti/db/relations.rb', line 115
def source_foreign_key
@source_foreign_key ||= @options[:source_foreign_key] || source_collection_class.implicit_foreign_key_name
end
|
#target_foreign_key ⇒ Object
119
120
121
|
# File 'lib/rasti/db/relations.rb', line 119
def target_foreign_key
@target_foreign_key ||= @options[:target_foreign_key] || target_collection_class.implicit_foreign_key_name
end
|