ruby-on-rails - 在 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.我可以在回调方法中使用查询吗?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_records
是Favorite
. 因此,您可以在内部访问用户self.user_id
(或者只是user_id
因为self
暗示),limit_records
并且不需要参数:
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