0

我在模型中有这个:

  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'
4

1 回答 1

0

看起来很简单的错别字。

第 7 行,如异常中所述:

commentable = @comment.commentable

所以,问题:

  • 你在打电话@comment.commentabe,但是@commentnil
  • 因此错误:undefined method 'commentable' for nil:NilClass
  • @commentnil您的 mailer 方法中,因为您将其作为commentNOT传递@comment,但您试图将其引用为@comment.

另外,为什么您要commentable作为参数传入,但在第 7 行您要commentable再次设置 - 这是多余的?commentable只需使用您作为参数传入的已经可用的变量。实际上,您似乎使用多个变量来执行此操作,但我无法判断(因为您没有显示邮件模板)您是否实际使用它们。

可能是您可以使用更简单的东西,例如:

所以,这应该(可能)工作:

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

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

于 2012-12-01T00:56:47.687 回答