如何将自我从模型传递到服务对象
How to pass self from model to service object
我想将 def track_item_added
从模型移动到服务对象中。
型号:
class Order < ApplicationRecord
has_many :order_items
has_many :items, through: :order_items, after_add: :track_item_added
private
def track_item_added
aft = AutoFillTotal.new(self)
aft.multiply_cost_and_quantity
end
end
和我的服务对象
class AutoFillTotal
def initialize(order)
@order = order
end
def multiply_cost_and_quantity
@order.items.pluck(:cost).zip(@order.order_items.pluck(:quantity)).
map{|x, y| x * y}.sum
end
end
现在在对象服务中是在 def track_item_added
中,但是现在当我启动这个函数时出现错误
Traceback (most recent call last):
2: from (irb):2
1: from app/models/order.rb:7:in `track_item_added'
ArgumentError (wrong number of arguments (given 1, expected 0))
可能是我在构造函数(新)中传递自己的问题
use only in association callback
has_many :items, through: :order_items, after_add: :track_item_added
after_add
回调需要一个参数。
https://guides.rubyonrails.org/v5.1/association_basics.html#association-callbacks
Rails passes the object being added or removed to the callback.
我想将 def track_item_added
从模型移动到服务对象中。
型号:
class Order < ApplicationRecord
has_many :order_items
has_many :items, through: :order_items, after_add: :track_item_added
private
def track_item_added
aft = AutoFillTotal.new(self)
aft.multiply_cost_and_quantity
end
end
和我的服务对象
class AutoFillTotal
def initialize(order)
@order = order
end
def multiply_cost_and_quantity
@order.items.pluck(:cost).zip(@order.order_items.pluck(:quantity)).
map{|x, y| x * y}.sum
end
end
现在在对象服务中是在 def track_item_added
中,但是现在当我启动这个函数时出现错误
Traceback (most recent call last):
2: from (irb):2
1: from app/models/order.rb:7:in `track_item_added'
ArgumentError (wrong number of arguments (given 1, expected 0))
可能是我在构造函数(新)中传递自己的问题
use only in association callback
has_many :items, through: :order_items, after_add: :track_item_added
after_add
回调需要一个参数。
https://guides.rubyonrails.org/v5.1/association_basics.html#association-callbacks
Rails passes the object being added or removed to the callback.