5

私には次のようなオブザーバーがいます:

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

基本的に私が使用しているのは、誰かが写真の1つにコメントを投稿したときに、特定のユーザーに簡単な通知メッセージを作成することだけです。

これはエラーメッセージで失敗します:

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

含めるActionView::Helpers::UrlHelperとそれが解決すると思っていたのですが、効果がないようです。

では、どうすればURLヘルパーをオブザーバーに含めることができますか、それとも他の方法でこれをレンダリングできますか?私は喜んで「メッセージビュー」を部分的または何かに移動しますが、オブザーバーにはこれを移動するための関連するビューがありません...

4

3 に答える 3

3

メッセージがページにレンダリングされたときにメッセージを作成してから、このようなものを使用してキャッシュしないのはなぜですか?

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

これにより、オブザーバーをハックする必要がなくなり、Railsではより「標準に準拠」するようになります。

于 2011-06-20T21:52:39.300 に答える
3

この種のことを処理するために、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
于 2011-06-22T20:08:50.223 に答える
2

link_toしたがって、メーラービューで使用できないのと同じ理由で、これを実行できないことがわかります。オブザーバーは現在のリクエストに関する情報を持っていないため、リンクヘルパーを使用できません。あなたはそれを別の方法でしなければなりません。

于 2011-06-22T20:01:05.257 に答える