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

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

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

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(应用中的实际评论 View )

<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(这些评论的 Controller )

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

最佳答案

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

然后在模板中,使用@comment 引用即可。

关于ruby-on-rails - Rails Mailer - 无法从 Mailer View 访问实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43082581/

相关文章:

ruby-on-rails - 如何通过 cron 运行 rake 任务?

ruby-on-rails - Rails + Filepicker gem : how to allow to upload only images?

css - 如何用不同栏和行上的帖子组织我的观点

ruby-on-rails - 如何防止嵌套创建在 ActiveRecord 中使用作用域 has_many 失败?

ruby-on-rails-3 - 发送消息所需的发件人(返回路径、发件人或发件人)

ruby-on-rails - 为 rails 设置 sendgrid..returning 授权错误

ruby-on-rails-3 - Ruby on Rails 3.2 Mailer,将邮件主题字段本地化

javascript - Rails Javascript 不执行

ruby-on-rails - Rails 3.0 中的 Arel 究竟是什么?

ruby-on-rails - Heroku 生产环境上的 FactoryBot