ruby-on-rails - 如何将自我从模型传递到服务对象
问题描述
我想将 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 的问题(新)
解决方案
仅在关联回调中使用
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 将要添加或删除的对象传递给回调。
推荐阅读
- matlab - matlab从二维数组中选择元素
- arrays - Swift - 在字典中插入数组数据
- java - Kakfa 0.10.2.1 生产者关闭方法问题
- python - Docx-Python 更改文本不透明度
- unit-testing - 如何使用 Mocha 和 Vue Test Utils 在 VueJS 中测试计算属性
- java - Eclipse 插件开发初学者
- java - @ManyToOne 中的 JPA @ManyToOne 无法正常工作
- java - 从不同的类调用 jdbc 连接得到“java.lang.ClassNotFoundException:oracle.jdbc.driver.OracleDriver”
- docker - Macos 高山 docker-compose.yml 和 .env
- python - 如何识别多变量时间序列预测模型中每个特征的时间延迟