首页 > 解决方案 > 如何将自我从模型传递到服务对象

问题描述

我想将 deftrack_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

现在在对象服务中是在 deftrack_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 的问题(新)

标签: ruby-on-railsrubyactiverecordservice-object

解决方案


仅在关联回调中使用

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


推荐阅读