Frage

I'm new to rails, and reading some rails code: 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

What can we know from this code? e.g.

  1. Because it's name is UserActionObserver, so it's a Observer of model UserAction?
  2. It observe: :post_action, :topic, :post, :notification, :topic_user, what do these fields mean? The will be created or just some references to some fields of other model?
  3. When will the method after_save will be invoked, and what is the model argument?
War es hilfreich?

Lösung

The observer class name can be any name. What really matters is this line

observe :post_action, :topic, :post, :notification, :topic_user

which observes objects created under PostAction, Topic, Post, Notification and TopicUser

The after_save is called after creating and updating a record. The passed argument is the actual object involved so it can be an instance of any of the 5 observed model. Using model as the parameter name is a bit misleading so you should change that to something like record

UPDATE: from the api

Observers will by default be mapped to the class with which they share a name. So CommentObserver will be tied to observing Comment, ProductManagerObserver to ProductManager, and so on. If you want to name your observer differently than the class you’re interested in observing, you can use the Observer.observe class method which takes either the concrete class (Product) or a symbol for that class (:product)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top