@@ -55,7 +55,7 @@ address.errors.to_h # => {}
55
55
56
56
### Serialization with ActiveRecord
57
57
58
- The value object class can be used as the coder for the ` serialize ` method:
58
+ For columns of ` json ` type, the value object class can be used as the coder for the ` serialize ` method:
59
59
60
60
``` ruby
61
61
class Customer < ActiveRecord ::Base
@@ -69,6 +69,14 @@ customer.reload
69
69
customer.home_address # => #<AddressValue:0x00ba9876543210 @street="123 Big Street", @postcode="12345", @city="Metropolis">
70
70
```
71
71
72
+ For columns of ` string ` or ` text ` type, wrap the value object class in a ` JsonCoder ` :
73
+
74
+ ``` ruby
75
+ class Customer < ActiveRecord ::Base
76
+ serialize :home_address , ValueObjects ::ActiveRecord ::JsonCoder .new (AddressValue )
77
+ end
78
+ ```
79
+
72
80
### Validation with ActiveRecord
73
81
74
82
By default, validating the record does not automatically validate the value object.
@@ -112,6 +120,26 @@ customer.home_address # => #<AddressValue:0x00ba9876503210 @street="321 Main St"
112
120
113
121
This is functionally similar to what ` accepts_nested_attributes_for ` does for associations.
114
122
123
+ Also, ` value_object ` will use the ` JsonCoder ` automatically if it detects that the column type is ` string ` or ` text ` .
124
+
125
+ Additional options may be passed in to customize validation:
126
+
127
+ ``` ruby
128
+ class Customer < ActiveRecord ::Base
129
+ include ValueObjects ::ActiveRecord
130
+ value_object :home_address , AddressValue , allow_nil: true
131
+ end
132
+ ```
133
+
134
+ Or, to skip validation entirely:
135
+
136
+ ``` ruby
137
+ class Customer < ActiveRecord ::Base
138
+ include ValueObjects ::ActiveRecord
139
+ value_object :home_address , AddressValue , no_validation: true
140
+ end
141
+ ```
142
+
115
143
### Value object collections
116
144
117
145
Serialization and validation of value object collections are also supported.
0 commit comments