0

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)

Trs MTV
  • 57
  • 5
  • 3
    "problem in that i pass self in constructor" - nope, not that. Something else. – Sergio Tulentsev Jul 01 '19 at 10:21
  • 1
    The error states that you've called the method with 1 argument, when it expects 0 arguments. This has got nothing to do with your question. What's the full stack trace? Where are you calling the method? – Tom Lord Jul 01 '19 at 10:51
  • use only in association callback `has_many :items, through: :order_items, after_add: :track_item_added` – Trs MTV Jul 01 '19 at 10:55
  • for test callback i run such commands in rails console: => order = Order.create; order.items << Item.first. after last command output this error – Trs MTV Jul 01 '19 at 10:57

1 Answers1

2

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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367