如何将自身从模型传递到服务对象

时间:2019-07-01 10:16:39

标签: ruby-on-rails ruby activerecord 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))

可能是我在构造函数(新)中传递self的问题

1 个答案:

答案 0 :(得分:2)

  

仅在关联回调中使用

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将要添加或删除的对象传递给回调。