@@ -52,41 +52,43 @@ class CreateOrder
52
52
extend Dry ::Initializer
53
53
54
54
# Params and options
55
- param :customer , model: ' Customer' # use either a name
56
- option :product , model: Product # or a class
55
+ param :customer , model: ' Customer' # use either a name
56
+ option :product , model: Product # or a class
57
+ option :coupon , model: Coupon .where(active: true ) # or relation
57
58
58
59
def call
59
- Order .create customer: customer, product: product
60
+ Order .create customer: customer, product: product, coupon: coupon
60
61
end
61
62
end
62
63
```
63
64
64
65
Now you can assign values as pre-initialized model instances:
65
66
66
67
``` ruby
67
- customer = Customer .find(1 )
68
- product = Product .find(2 )
69
-
70
- order = CreateOrder .new (customer, product: product).call
71
- order.customer # => <Customer @id=1 ...>
72
- order.product # => <Product @id=2 ...>
68
+ customer = Customer .create(id: 1 )
69
+ product = Product .create(id: 2 )
70
+ coupon = Coupon .create(id: 3 , active: true )
71
+
72
+ order = CreateOrder .new (customer, product: product, coupon: coupon).call
73
+ order.customer # => #<Customer @id=1 ...>
74
+ order.product # => #<Product @id=2 ...>
75
+ order.coupon # => #<Coupon @id=3 ...>
73
76
```
74
77
75
78
...or their ids:
76
79
77
80
``` ruby
78
- order = CreateOrder .new (1 , product: 2 ).call
79
- order.customer # => <Customer @id=1 ...>
80
- order.product # => <Product @id=2 ...>
81
+ order = CreateOrder .new (1 , product: 2 , coupon: 3 ).call
82
+ order.customer # => #<Customer @id=1 ...>
83
+ order.product # => #<Product @id=2 ...>
84
+ order.coupon # => #<Coupon @id=3 ...>
81
85
```
82
86
83
- The instance is envoked using method ` find_by(id: ...) ` .
84
- With wrong ids ` nil ` values are assigned to a corresponding params and options:
87
+ The instance is envoked using method ` find_by!(id: ...) ` .
85
88
86
89
``` ruby
87
- order = CreateOrder .new (0 , product: 0 ).call
88
- order.customer # => nil
89
- order.product # => nil
90
+ order = CreateOrder .new (1 , product: 2 , coupon: 4 ).call
91
+ # raises #<ActiveRecord::RecordNotFound>
90
92
```
91
93
92
94
You can specify custom ` key ` for searching model instance:
0 commit comments