Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to add a newly created user's email address to MailChimp?

For context, I am developing a web application using Ruby on Rails and I am using MailChimp for handling email campaigns.

Given an ActiveRecord Model named User with an attribute named email, how might I send a user's email to a MailChimp List upon the successful creation of a new user?

like image 601
sja Avatar asked Dec 26 '22 06:12

sja


2 Answers

Add the official mailchimp-api gem to your Gemfile:

gem 'mailchimp-api', require: 'mailchimp'

Then run:

bundle install

Use an after_create hook in your User model to send the subscriber to MailChimp:

class User < ActiveRecord::Base

  after_create :add_mailchimp_subscriber


  def add_mailchimp_subscriber
    client = Mailchimp::API.new('<your mailchimp api key>')
    client.lists.subscribe('<your mailchimp list id>', {email: email}, {'FNAME' => first_name, 'LNAME' => last_name})
  end
end

That's the minimum you'll need to add the subscriber to MailChimp. You may want to move the add_mailchimp_subscriber logic to it's own class or queue a job to run it asynchronously. You should also add some error handling. The client.lists.subscribe method will raise errors specific to the problem. For example, if the MailChimp list id you specify is not valid you will get a Mailchimp::ListDoesNotExistError.

You can find the official gem and docs here:

https://bitbucket.org/mailchimp/mailchimp-api-ruby/

like image 125
infused Avatar answered Dec 30 '22 22:12

infused


Basically, what you need is Callbacks. You can write code to subscribe your new user to mailchimp in after_create callback.

Something like in your user.rb model.

def after_create(user)
  # code to subscribe user to mailchimp
end

You can have a look on this blog for more and an example.

like image 27
RAJ Avatar answered Dec 30 '22 21:12

RAJ