Ruby on rails Rails:在Observer中使用URL帮助器
我有一个观察者,看起来像这样:Ruby on rails Rails:在Observer中使用URL帮助器,ruby-on-rails,ruby-on-rails-3,observer-pattern,link-to,url-helper,Ruby On Rails,Ruby On Rails 3,Observer Pattern,Link To,Url Helper,我有一个观察者,看起来像这样: 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 pho
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
class CommentObservercomment.photo.user,:message=>message)
结束
结束
基本上,我用它所做的就是当有人在某张照片上发表评论时,为某个用户创建一条简单的通知消息
此操作失败,并显示错误消息:
NoMethodError (undefined method `link_to' for #<CommentObserver:0x00000102fe9810>):
NoMethodError(未定义的方法'link#to'表示#):
我本以为包含ActionView::Helpers::UrlHelper
可以解决这个问题,但似乎没有效果
那么,我如何在我的观察者中包含URL帮助器,或者以其他方式呈现它呢?我很乐意将“消息视图”移动到部分或其他位置,但是观察者没有相关的视图将其移动到…为什么不在消息呈现到页面时构建消息,然后使用类似的方式缓存它
<% cache do %>
<%= render user.notifications %>
<% end %>
这将避免您在observer中进行黑客攻击,并且在Rails中更加“符合标准”。因此,事实证明,这无法实现,原因与您不能在邮件视图中使用
链接到
相同。观察者没有关于当前请求的信息,因此无法使用链接帮助器。你必须用另一种方式来做。为了处理这类事情,我制作了一个AbstractController来生成电子邮件的正文,然后将其作为变量传递给mailer类:
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