在评论创建时在Rails App中发送电子邮件通知

时间:2013-01-22 20:41:07

标签: ruby-on-rails ruby email ruby-on-rails-3.2

我正在使用gem'外国人'并为我的应用程序设置评论,一切正常。但是,我还想在创建评论时通知我的用户。我有两个用户,客户和开发人员。客户可以发表评论,开发人员可以发表评论。

如何设置我的comments_controller.rb文件以确定其客户或开发人员是否发布了评论,然后使用正确的模板发送电子邮件。

到目前为止,我已经尝试过以下工作而没有工作;

  def create
    @comment = Comment.new(params[:comment])

    respond_to do |format|
      if @comment.save
        if current_user.is_developer?
           Notifier.developer_notify(@developer).deliver
        elsif current_user.is_customer?
           Notifier.customer_notify(@customer).deliver
        end
        format.html { redirect_to :back, notice: 'Comment was successfully created.' }
        # format.json { render json: @comment, status: :created, location: @comment }
      else
        format.html { render action: "new" }
        # format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

“developer_notify”和“customer_notify”是我的通告程序邮件程序中定义的类。

到目前为止,我的“Notifier”邮件看起来像这样;

  def developer_notify(joblisting)
    @joblisting = joblisting
    mail(:to => @joblisting.current_user.email, :subject => "There's a new comment.")
  end

@Joblisting是引用的作业,因为每个Joblisting都有自己的客户和开发人员的评论。

执行上述操作时,会出现错误 - undefined method 'current_user' for nil:NilClass

所以我猜它没有找到工作列表ID,也没有找到客户的电子邮件地址,如果客户发布了同一工作的评论,它会向开发人员发送电子邮件,并发布新评论的通知。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您已从控制器传递joblisting

def create
 @comment = Comment.new(params[:comment])
 #you have define here joblisting for example:
  joblisting = JobListing.first #adapt the query to your needs
 respond_to do |format|
  if @comment.save
    if current_user.is_developer?
       #here add joblisting as argument after @developer
       Notifier.developer_notify(@developer, joblisting).deliver
    elsif current_user.is_customer?
       #here add joblisting as argument after @developer
       Notifier.customer_notify(@customerm, joblisting).deliver
    end
    format.html { redirect_to :back, notice: 'Comment was successfully created.' }
    # format.json { render json: @comment, status: :created, location: @comment }
  else
    format.html { render action: "new" }
    # format.json { render json: @comment.errors, status: :unprocessable_entity }
  end
 end
end
通知邮件上的

def developer_notify(@developer, joblisting)
    @joblisting = joblisting
    mail(:to => @joblisting.current_user.email, :subject => "There's a new comment.")
  end

问候!