我有一个UnreadEntry模型并使用after_commit
回调来向推送服务发送通知。问题是在添加记录时事件触发正常,但在模型上发送delete_all
时,after_commit
,after_destroy
都不会被触发。
如何添加catch delete_all并为其添加回调?
class UnreadEntry < ActiveRecord::Base
belongs_to :user
belongs_to :feed
belongs_to :entry
after_commit :send_pusher_notification, if: PUSHER_ENABLED
validates_uniqueness_of :user_id, scope: :entry_id
def self.create_from_owners(user, entry)
create(user_id: user.id, feed_id: entry.feed_id, entry_id: entry.id, published: entry.published, entry_created_at: entry.created_at)
end
def self.sort_preference(sort)
if sort == 'ASC'
order("published ASC")
else
order("published DESC")
end
end
def send_pusher_notification(user = nil, from = 'UnreadEntry#callback')
if user.nil?
unread_count = UnreadEntry.where(user_id: self.user_id).count
else
unread_count = UnreadEntry.where(user_id: user.id).count
end
Pusher['rssapp'].trigger('unread_count', {
message: unread_count
})
end
end
答案 0 :(得分:2)
简单 - 不要使用delete_all
。 delete_all
和update_all
专门用于直接查询数据库,绕过ActiveRecord模型逻辑 - 包括验证和回调。如果您想要回调,请分别在每个模型实例上调用destroy
。
my_collection.each(&:destroy)