如何将评论传递给邮件程序?

时间:2012-12-01 00:37:40

标签: ruby-on-rails mailer

我在模型中有这个:

  after_create do |comment|
   CommentMailer.comment_email(self).deliver
  end

这在CommentMailer中:

  class CommentMailer < ActionMailer::Base
  helper ActionView::Helpers::UrlHelper
  include CommentHelper
  helper :comment
 def comment_email(user, comment, commentable)
   mail(to: user.email,
        subject: "You have left a comment",
        from: "comments@lumeo.com",
        bcc: "brian@lumeo.com")
 end
end

这是在CommentHelper:

module CommentHelper
  def find_commentable
    @comment = Comment.find(params[:comment])
    params.each do |name, value|
      if name =~ /(.+)_id$/
        return $1.classify.constantize.find(value)
      end
    end
    nil
  end
end

我收到了这个错误:

Started POST "/requests/6/comments" for 127.0.0.1 at 2012-11-30 17:28:55 -0800
Processing by CommentsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"R62NH5/EE34FPapEqy7mfpa0wKz18GtSdhH8MGYq2Ec=", "comment"=>{"content"=>"post", "show"=>"true"}, "commit"=>"Create Comment", "request_id"=>"6"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY users.created_at DESC LIMIT 1
  Request Load (0.3ms)  SELECT "requests".* FROM "requests" WHERE "requests"."id" = $1 LIMIT 1  [["id", "6"]]
  CACHE (0.0ms)  SELECT "requests".* FROM "requests" WHERE "requests"."id" = $1 LIMIT 1  [["id", "6"]]
   (0.1ms)  BEGIN
  SQL (0.4ms)  INSERT INTO "comments" ("commentable_id", "commentable_type", "content", "created_at", "show", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["commentable_id", 6], ["commentable_type", "Request"], ["content", "post"], ["created_at", Sat, 01 Dec 2012 01:28:55 UTC +00:00], ["show", true], ["updated_at", Sat, 01 Dec 2012 01:28:55 UTC +00:00], ["user_id", 2]]
   (0.2ms)  ROLLBACK
Completed 500 Internal Server Error in 136ms

ArgumentError (wrong number of arguments (1 for 3)):
  app/mailers/comment_mailer.rb:5:in `comment_email'
  app/models/comment.rb:27:in `block in <class:Comment>'
  app/controllers/comments_controller.rb:22:in `create'

1 个答案:

答案 0 :(得分:0)

看起来像简单的错别字。

第7行,如异常中所述:

commentable = @comment.commentable

所以,问题:

  • 您正在呼叫@comment.commentabe,但@commentnil
  • 因此错误:undefined method 'commentable' for nil:NilClass
  • @comment在您的邮件程序方法中为nil,因为您将其作为comment NOT @comment传递,但您尝试将其作为{{1}引用}}。

另外,为什么你传递@comment作为参数,但是在第7行你再次设置commentable - 这是多余的?只需使用您传入的已知commentable变量作为参数。事实上,你似乎是用几个变量来做这件事,但我不知道(因为你没有显示邮件模板)你是否真正使用它们。

可能你可以使用更简单的东西:

所以,这应该(可能)有效:

commentable

如果你发布你的邮件模板(这样我就可以看到电子邮件的正文),我可以帮助你将变量放到模板中。