5

我有一個觀察者,看起來像這樣:Rails的:使用URL助手在觀察

class CommentObserver < ActiveRecord::Observer 
    include ActionView::Helpers::UrlHelper 

    def after_create(comment) 
     message = "#{link_to comment.user.full_name, user_path(comment.user)} commented on #{link_to 'your photo',photo_path(comment.photo)} of #{comment.photo.location(:min)}" 
     Notification.create(:user=>comment.photo.user,:message=>message) 
    end 

end 

基本上所有我用它做的是創建一個簡單的通知消息針對特定用戶,當有人張貼評論在他們的一張照片上。

這失敗的錯誤消息:

NoMethodError (undefined method `link_to' for #<CommentObserver:0x00000102fe9810>): 

我本來期望包括ActionView::Helpers::UrlHelper會解決這個問題,但它似乎沒有任何效果。

那麼,我該如何在我的觀察者中包含URL助手,或者以其他方式呈現這個?我會很高興地將「消息視圖」移動到部分內容中,但觀察者沒有相關視圖來移動它...

回答

2

所以,事實證明,這不能出於同樣的原因,你不能在郵件視圖中使用link_to。觀察者沒有關於當前請求的信息,因此不能使用鏈接助手。你必須以不同的方式去做。

3

爲什麼不在構建消息時將其呈現給頁面,然後使用這樣的東西緩存它?

<% cache do %> 
    <%= render user.notifications %> 
<% end %> 

這將節省您不得不在觀察者中進行破解,並且在Rails中更符合「符合標準」。

+0

這不一定會發送電子郵件。我正在嘗試創建一個可用於創建通知的簡單模型(例如,當某人發佈針對您的問題的答案時,會發生堆棧溢出問題)。根據用戶的設置,通知可以通過電子郵件發送消息或者將其放在用戶儀表板上。這位觀察者只是簡單地創建一條與正在創建的評論相關的通知消息。如果您對整個系統有更好的建議,請告訴我,今天我一直在害我,我一直沒能找到一個很好的例子來研究這種通知系統。 – Andrew

+0

...恩,我認爲你編輯後,我已經評論... :)我從來沒有使用過「緩存」之前 - 這是如何工作的? – Andrew

2

爲了處理這種類型的事情,我做了一個AbstractController生成電子郵件的正文,然後我通過在作爲一個變量給寄件人類:

class AbstractEmailController < AbstractController::Base 

    include AbstractController::Rendering 
    include AbstractController::Layouts 
    include AbstractController::Helpers 
    include AbstractController::Translation 
    include AbstractController::AssetPaths 
    include Rails.application.routes.url_helpers 
    include ActionView::Helpers::AssetTagHelper 

    # Uncomment if you want to use helpers 
    # defined in ApplicationHelper in your views 
    # helper ApplicationHelper 

    # Make sure your controller can find views 
    self.view_paths = "app/views" 
    self.assets_dir = '/app/public' 

    # You can define custom helper methods to be used in views here 
    # helper_method :current_admin 
    # def current_admin; nil; end 

    # for the requester to know that the acceptance email was sent 
    def generate_comment_notification(comment, host = ENV['RAILS_SERVER']) 
     render :partial => "photos/comment_notification", :locals => { :comment => comment, :host => host } 
    end 
    end 

在我的觀察:

def after_create(comment) 
    email_body = AbstractEmailController.new.generate_comment_notification(comment) 
    MyMailer.new(comment.id, email_body) 
    end