forked from mongoid/mongoid-site
/
relations.html.haml
84 lines (65 loc) · 2.26 KB
/
relations.html.haml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
- content_for :head do
%title Mongoid: Relations
%h1 relations
%p
Relations are associations between one model and another in the domain
and in the database. Embedded relations describe documents who are
stored inside other documents in the database. Referenced relations
describe documents that reference documents in another collection by
storing data (usually an id) about the other document in itself.
%p
All relation objects in Mongoid are proxies to the actual document or
documents themselves, which provide extra functionality for accessing,
replacing, appending and persisting.
%h2 commonalities between all relations
%h3 attributes
%p
All relations contain a <tt>target</tt>, which is the proxied document
or documents, a <tt>base</tt> which is the document the relation hangs
off, and <tt>metadata</tt> which provides information about the relation.
:coderay
#!ruby
class Person
include Mongoid::Document
embeds_many :addresses
end
person.addresses = [ address ]
person.addresses.target #=> returns [ address ]
person.addresses.base #=> returns person
person.addresses.metadata #=> returns the metadata
%h3 extensions
%p
All relations can have extensions, which provides a way to add
application specific functionality to the relation. They are defined by
providing a block to the relation definition.
:coderay
#!ruby
class Person
include Mongoid::Document
embeds_many :addresses do
def find_by_country(country)
where(country: country).first
end
def chinese
@target.select { |address| address.country == "China"}
end
end
end
person.addresses.find_by_country('Mongolia') #=> returns address
person.addresses.chinese #=> returns [ address ]
%h3 custom relation names
%p
You can name your relations whatever you like, but if the class cannot be
inferred by Mongoid from the name, and neither can the opposite side you'll
want to provide the macro with some additional options to tell Mongoid
how to hook them up.
:coderay
#!ruby
class Lush
include Mongoid::Document
embeds_one :whiskey, class_name: "Drink", inverse_of: :alcoholic
end
class Drink
include Mongoid::Document
embedded_in :alcoholic, class_name: "Lush", inverse_of: :whiskey
end