Maurice Maurice - 1 month ago 12
Ruby Question

Email notification when friend request is sent and accepted in rails

I implemented the has_friendship gem in my rails app for friendship requests. I now want email notifications when a friend request is sent and when it's accepted (for example user A sends request to B, B gets notified. User B accepts the request and A gets notified. these are the controller actions I have for sending and accepting friend requests:

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


I played around with the actionmailer but couldn't get it to work.
Here's what I have so far for the mailer methods:

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


I'm using Sendgrid. Any help would be much appreciated.
Thanks

Answer

Adding the mailer methods to your methods should work

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
Comments