rails 模型中如何导致关联回调

How cause association callback in rails models

如何在模型中跟踪这个命令

=> order = Order.create
=> order.items << Item.first // this command

如果我有这样的模型:

class Order < ApplicationRecord
   has_many :order_items
   has_many :items, through: :order_items
end
class Item < ApplicationRecord
   has_many :order_items
   has_many :orders, through: :order_items
end
class OrderItem < ApplicationRecord
   belongs_to :order
   belongs_to :item
end

我尝试使用after_add,但我没有成功。 例如我的任务: 在控制器的 (OrderController) 方法中创建:

def create
 @order = Order.create(order_params)
 @order.items << Item.find(params[:id])
end

而且我有模型订单或项目跟踪此(当我将项目添加到订单时)并在控制台中打印消息(例如)

查看有关 Association Callbacks 的 Rails 指南。例如,有一个 after_add 回调。

# in your Order model
has_many :items, after_add: :track_item_added

private

def track_item_added(item)
  # your tracking code, for example
  Rails.logger.debug("Item ##{item.id} added to order ##{id}")
end