Reputation: 347
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?
Upvotes: 4
Views: 1903
Reputation: 24337
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/
Upvotes: 8
Reputation: 2945
You can use Mailchimp API for managing list subscribers: http://apidocs.mailchimp.com/api/2.0/lists/subscribe.php
There are several ruby wrappers for ease of use in rails: http://apidocs.mailchimp.com/api/downloads/#ruby-rails
So, the common approach to add some actions on model changes is to use Active Records callbacks. So your code may look like this
class User < ActiveRecord::Base
after_create :add_subscriber_to_list
private
def add_subscriber_to_list
# Logic to add subscriber to list via Mailchimp API ruby wrapper
end
end
Upvotes: 0
Reputation: 9747
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.
Upvotes: 2