2014-02-21 61 views
2

我使用merit gem鋼軌,並想擁有的聲譽變化的時間表,贏得徽章等。例如Rails的功勳寶石,如何顯示聲譽的時間表改變

  • +1 22Feb PostTitle投了起來
  • +3 22Feb郵政標題收藏
  • -1 22Feb PostTitle投了下來......等等。

基礎上的自述,我創建了以下內容:

配置/初始化/ merit.rb

config.add_observer 'ReputationChangeObserver' 

reputation_change_observer.rb

class ReputationChangeObserver 
    def update(changed_data) 
    # `changed_data[:description]` holds information on what changed 
    # badges granted or removed, points changed. 

    # `changed_data[:merit_object]` reputation related object created by merit. 
    # It responds to `sash_id` and `sash`. From there you can get to your 
    # application object that had it's reputation changed, for example: 
    # sash_id = changed_data[:merit_object].sash_id 
    # User.where(sash_id: sash_id).first 

    # You may use this to fill a timeline with notifications for users, send 
    # emails, etc. 

    end 
end 

問題, 接下來是什麼?我如何使用觀察者顯示current_user.changed_data的時間表?

回答

2

API似乎現在有點不舒服,反正這裏的示例代碼,在當前的功德主(1515c6463f92aaace6298015c0f8e70064885779)工作原理:

class ReputationChangeObserver 
    def update(changed_data) 
    # description will be something like: 
    # granted 5 points 
    # granted just-registered badge 
    # removed autobiographer badge 
    description = changed_data[:description] 

    # If user is your meritable model, you can grab it like: 
    if changed_data[:merit_object] 
     sash_id = changed_data[:merit_object].sash_id 
     user = User.where(sash_id: sash_id).first 
    end 

    # To know where and when it happened: 
    merit_action = Merit::Action.find changed_data[:merit_action_id] 
    controller = merit_action.target_model 
    action = merit_action.action_method 
    when = merit_action.created_at 

    # From here on, you can create a new Notification assuming that's an 
    # ActiveRecord Model in your app, send an email, etc. For example: 
    Notification.create(
     user: user, 
     what: description, 
     where: "#{controller}##{action}", 
     when: when) 
    end 
end 

編輯:請注意,因爲這個答案是API發生了變化,看到https://github.com/tute/merit#getting-notifications

+0

謝謝tute!愛寶石。爲了清楚起見,我將不得不創建一個Notification模型並使用user_id進行遷移,在什麼地方和何時使用列? –

+0

我認爲要實現一個通知系統,就像您在文章中描述的一樣,您需要按照以下方式進行遷移:'rails g遷移通知user_id:integer,什麼,何處,何時:datetime'。最好! – TuteC

+0

好吧,當我得到它的工作時,會給它一個完整的代碼。非常感謝! –