Rails Mailer - 无法从Mailer View访问实例变量

时间:2017-03-29 01:14:23

标签: ruby-on-rails ruby-on-rails-5 actionmailer instance-variables mailer

我有一个rails邮件程序,当用户回复其他用户的评论时,它会在当前成功发送电子邮件。 (电子邮件发送给回复的人)。我正在尝试在电子邮件正文中添加一些动态内容,例如回复者的用户名和该用户的评论本身。我不确定如何在new_reply.html.erb视图中抓取该特定评论,以便在我发送的电子邮件中正确显示...我的代码如下:

views / comment_mailer / new_reply.html.erb(电子邮件内容)

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <table width="100%">

        <h2 style="color: #428bca">You have a new reply.</h2>
            <p>Someone replied with the following comment...</p>

      <p><%= comment.body %></p>

            <p>To reply back, login to the app...</p>

        </table>
  </body>
</html>

views / comments / _comment.html.erb(应用中的实际评论视图)

<div class="well">
  <p class="text-muted">Added on
    <%= l(comment.created_at, format: '%B, %d %Y %H:%M:%S') %></p>

  <blockquote>
    <p><%= comment.body %></p>
        <p><%= link_to 'reply', new_comment_path(comment.id) %></p>
  </blockquote>
</div>

mailers / comment_mailer.rb(我的评论邮件)

class CommentMailer < ApplicationMailer
    default from: "notifications@app.com"

    def new_reply(parent_comment)
    owner = parent_comment.owner
        mail(to: owner.email, subject: 'New reply to one of your comments')
    end
end

controllers / model_comments_controller.rb(这些评论的控制器)

def create
    @taskrelationship = commentable_type.constantize.find(commentable_id)
    @project = @taskrelationship.taskproject
    @new_comment = Comment.build_from(@taskrelationship, current_user.id, body)
    if @new_comment.save

      # create the notification
      (@taskrelationship.taskproject.followers.uniq - [current_user]).each do |user|
        Notification.create(recipient: user, actor: current_user, action: "posted", notifiable: @new_comment)
      end

      make_child_comment
    end
    render 'projects/show_project_task_comments', layout: false
  end

private

def make_child_comment
  return if comment_id.blank?

  parent_comment = Comment.find comment_id
  @new_comment.move_to_child_of(parent_comment)
  CommentMailer.new_reply(parent_comment).deliver
end

1 个答案:

答案 0 :(得分:1)

在邮件程序的new_reply方法中,声明一个实例变量@comment,它引用您要使用的评论。

然后在模板中,只需使用@comment来引用它。