在 Rails 中将参数传递给回调

Pass parameter to callback in Rails

我有 2 个模型:用户和收藏夹。在模型收藏夹中:

class Favorite < ApplicationRecord
  belongs_to :user, foreign_key: :user_id

  def self.add_favorite(options)
    create!(options)
  end

  def self.unfavorite(options)
    where(options).delete_all
  end
现在,我想限制保存到收藏夹的记录数为 10。这意味着用户只喜欢 10 个产品。我研究了 google,有人说我尝试使用回调,我认为这是正确的方法,但它提出了 2 个问题: 1. 是否可以在回调方法中使用query? 2.回调可以传参吗?

我认为是示例代码:

class Favorite < ApplicationRecord
  after_create :limit_records(user_id)
  belongs_to :user, foreign_key: :user_id

  def self.add_favorite(options)
    create!(options)
  end

  def self.unfavorite(options)
    where(options).delete_all
  end

  def limit_records(user_id)
    count = self.where(user_id: user_id).count
    self.where(used_id: user_id).last.delete if count > 10
  end
如果用户有10个收藏,当他们喜欢任何商品时,创建收藏后会调用回调,如果是第11条记录将被删除。

您有:

belongs_to :user, foreign_key: :user_id

在您的 Favorite 模型中,limit_recordsFavorite 上的一个实例方法。因此,您可以在 limit_records 中以 self.user_id 的身份访问用户(或者只是 user_id,因为 self 是隐含的)并且不需要参数:

after_create :limit_records

def limit_records
  # same as what you have now, `user_id` will be `self.user_id`
  # now that there is no `user_id` argument...
  count = self.where(user_id: user_id).count
  self.where(used_id: user_id).last.delete if count > 10
end