【问题标题】:Email notification when friend request is sent and accepted in rails在 Rails 中发送和接受好友请求时的电子邮件通知
【发布时间】:2016-10-19 05:03:30
【问题描述】:

我在我的 rails 应用程序中实现了 has_friendship gem 来处理友谊请求。我现在想要在发送朋友请求并接受它时发送​​电子邮件通知(例如,用户 A 向 B 发送请求,B 收到通知。用户 B 接受请求并且 A 收到通知。这些是我用于发送和接受的控制器操作好友请求:

  def add_friend
    if current_user.friend_request(@friend)
      redirect_to my_friends_path, notice: "Friend request successfully sent."
    else
      redirect_to my_friends_path, flash[:error] = "There was an error sending the friend request"
    end
  end

  def accept_friend
    if current_user.accept_request(@friend)
      redirect_to my_friends_path, notice: "Friend request successfully accepted."
    else
      redirect_to my_friends_path, flash[:error] = "There was an error accepting the friend request."
    end
  end

我玩过 actionmailer,但无法让它工作。 到目前为止,这是我对邮件方法的了解:

class FriendshipNotifier < ApplicationMailer
  default :from => 'do-not-reply@example.com'

  def sent_friend_requests(@friend)
    @friend = friend
    mail( :to => @friend.email,
          :subject => 'You have received a friend request.' )
     end
  end

  def accepted_friend_requests(@friend)
    @friend = friend
    mail( :to => @friend.email,
          :subject => 'Your friend request has been accepted.' )
    end
  end
end

我正在使用 Sendgrid。任何帮助将非常感激。 谢谢

【问题讨论】:

  • 请显示您尝试的actionmailer代码。
  • couldn't get it to work. 非常模糊。你能告诉我们你观察到什么以及你期望观察到什么吗?您是否检查过您的配置/环境文件中有邮件设置?您是 Action Mailer 的新手吗?如果是这样,您是否阅读过有关该主题的 Rails 指南:guides.rubyonrails.org/action_mailer_basics.html
  • 抱歉,我并没有在终端中看到任何值得注意的东西。我期待看到电子邮件的结果。我确实在 config/environment 中设置了 sendgrid,因为我使用它在用户注册时发送电子邮件确认。我确实为此查看了 rails 指南,但我仍然无法使我的代码适应我想要完成的任务
  • sent_friend_requests(@friend) 更改为sent_friend_requests(friend)accepted_friend_requests(@friend)。如果 SO 问题中的拼写错误,请忽略它,否则请更改并试一试。
  • 你在哪里调用你的邮件方法?这个问题还不是一个可重复的例子

标签: ruby-on-rails ruby email actionmailer


【解决方案1】:

将邮件方法添加到您的方法应该可以工作

def add_friend
  if current_user.friend_request(@friend)
    FriendshipNotifier.send_friend_requests(@friend)
    redirect_to my_friends_path, notice: "Friend request successfully sent."
  else
    redirect_to my_friends_path, flash[:error] = "There was an error sending the friend request"
  end
end

def accept_friend
  if current_user.accept_request(@friend)
    FriendshipNotifier.accepted_friend_requests(@friend)
    redirect_to my_friends_path, notice: "Friend request successfully accepted."
  else
    redirect_to my_friends_path, flash[:error] = "There was an error accepting the friend request."
  end
end

【讨论】:

  • 我做到了,它在我的终端上工作。我可以在我的日志中看到这封电子邮件,但由于某种原因,这些电子邮件没有在生产中发送(我正在使用 Heroku)。任何想法为什么? @user3693398
  • 没关系,它工作得很好,只是需要一段时间才能收到电子邮件。非常感谢所有花时间看它的人:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-15
  • 2021-05-26
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多