1

I have a list of customers that I send emails using an ActionMailer mailer. I am trying to code a link at the bottom of each email so a customer can unsubscribe from a mailing. So far I have an opted_out field in my customers database, I am simply unsure how to properly set up the route and have it update the correct database field. I want to design this so the user can simply click the link and viola, unsubscribed.

in blast_mailer.rb

  def mail_blast(customer, blast)
    @customer = customer
    @blast =blast
#what conditional statement goes here?
    mail(:to => @customer.email, :subject => @blast.subject)
    @blast.update_attributes(:last_sent => DateTime.now)
  end

in mail_blast.html.erb

 <div style="font-family:Helvetica; font-size:12pt; font-style:italic; width:500px; height:auto;">
        <img src="http://www.ratatouillecatering.com/<%=asset_path("emailheader.png")%>" alt="Menu" />
        <br />
        <br />
        Dear <%= @customer.fname %> <br />

        <%= raw(@blast.content) =%> <br />
#what goes here? a link_to what?
        <br />
    </div>
ctilley79
  • 2,151
  • 3
  • 31
  • 64

1 Answers1

3

I would have a boolean field in the users table called something like subscribed. This way, you can just select all Users that are subscribed to the email.

User.where(:subscribed => true)

You can then set up an unsubscribe action in a controller that flips the boolean.

def unsubscribe
  User.find(params[:id]).update_attributes(:subscribed => false)
end

All you have to do is pass in a link to this action in the email template, and have the user's ID be passed in with it. The route can be setup so that the URL looks like www.example.com/users/<id>/unsubscribe.

jnevelson
  • 2,092
  • 2
  • 21
  • 31
  • 1
    That worked great. What if I would like to prevent another user from being able to access that url outside of the email. I don't want other customers able to unsubscribe anyone. – ctilley79 Mar 08 '12 at 04:19
  • 1
    Rather than using the RID of the user from the SQL table, have the ID be some randomly generated key that is created with the user. That way, you at least have some security through obscurity. Otherwise, you can setup the unsubscribe action to only work with a logged-in user (that makes the unsubscribe process multiple steps however - log in, and then unsubscribe). – jnevelson Mar 12 '12 at 16:37