ruby-on-railsrubyactiverecordservice-object

How to pass self from model to service object


I wanted to move def track_item_added from model into service object. Model:

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

and my service object

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

that now in object service was in def track_item_added but now when I start this function as I get an error

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))

May be it problem in that i pass self in constructor (new)


Solution

  • use only in association callback

    has_many :items, through: :order_items, after_add: :track_item_added
    

    after_add callbacks expect one parameter.

    https://guides.rubyonrails.org/v5.1/association_basics.html#association-callbacks

    Rails passes the object being added or removed to the callback.