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?
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With