将用户信息传递给邮件程序

时间:2014-04-03 14:13:02

标签: ruby-on-rails ruby ruby-on-rails-4

我有一篇帖子,里面有很多评论。我正在尝试向帖子的所有者发送通知电子邮件,有人评论了他们的帖子,但我很难将邮件的所有者送到邮件程序。代码如下:

class CommentsController < ApplicationController
def create

    @commentable = find_commentable
    @comment = @commentable.comments.build(comment_params)
    @comment.user_id = current_user.id

    if @comment.save
      flash[:notice] = "Successfully posted an offer."
      PostMailer.comment_posted(----).deliver #this is the mail code
      redirect_to @commentable
    else
      flash[:error] = "Error adding an offer."
    end
  end
end

下面是邮件代码

class PostMailer < ActionMailer::Base
  default from: "contact@example.com"

  def comment_posted(user)
    @user = user

    mail to: user.first_name, subject: "You have a new Comment!"
  end
end

下面是评论模型

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :commentable, :polymorphic => true
  has_ancestry
end

和Post模型

class Post < ActiveRecord::Base

    belongs_to :user
    has_many :comments, :as => :commentable, dependent: :destroy 
end

2 个答案:

答案 0 :(得分:1)

使用此:

PostMailer.comment_posted(@commentable.user).deliver

@commentable会针对给定的评论提供相应的Post记录。 发布所属的用户,因此您可以使用@commentable.user访问海报。

答案 1 :(得分:0)

我注意到你正在做的控制器:

PostMailer.comment_posted

不应该是:

PostMailer.offer_posted(@comment.user).deliver