我是rails的新手,并阅读了一些rails代码:https://github.com/discourse/discourse/blob/master/app/models/user_action_observer.rb#L1
class UserActionObserver < ActiveRecord::Observer
observe :post_action, :topic, :post, :notification, :topic_user
def after_save(model)
puts 'do something'
end
end
我们可以从这段代码中得知什么? e.g。
UserActionObserver
,所以它是模型UserAction
的观察者?:post_action, :topic, :post, :notification, :topic_user
,这些字段是什么意思?将创建或只是对其他模型的某些字段的一些引用?after_save
,model
参数是什么?答案 0 :(得分:2)
观察者类名可以是任何名称。真正重要的是这一行
observe :post_action, :topic, :post, :notification, :topic_user
观察在PostAction,Topic,Post,Notification和TopicUser
下创建的对象创建和更新记录后调用after_save
。传递的参数是涉及的实际对象,因此它可以是任何5个观察模型的实例。使用model
作为参数名称有点误导,因此您应该将其更改为record
更新:来自api
默认情况下,观察者将映射到与其共享名称的类。因此,CommentObserver将与观察Comment,ProductManagerObserver与ProductManager相关联,依此类推。如果要为观察者命名的方式与您要观察的类不同,可以使用Observer.observe类方法,该方法采用具体类(Product)或该类的符号(:product)