سؤال

I'd like to keep Mailchimp in sync with my user table.

I'd like to capture all of the devise fields (e.g. current_sign_in_at, sign_in_count etc) in the Mailchimp table and keep those up-to-date too.

The Mailchimp API integration is easy. What I want to know is how best to hook onto the User model, so that I can trigger my Mailchimp update method with the new record.

Also if anyone can explain why 'Dirty' is called that I would appreciate it!

هل كانت مفيدة؟

المحلول

As for your first question, there are many callbacks ActiveRecord supplies that you can hook to in order to update Mailchimp as necessary. You can use after_create if you want to update Mailchimp only with new users and after_update if you want to update Mailchimp of an existing user data. You can read the full documentation of callbacks here.

Dirty is a common way to indicate that some data has changed but has not yet persisted. In ActiveRecord, it means that an attribute of a model has changed but has not been saved to the database yet. So when I write @some_user.username = 'some_user_name' I made the username attribute of @some_user dirty. Once I issue @some_user.save! the attribute is persisted and no longer referred as dirty attribute.

The combination of both of this concepts is what you are looking for. For example:

class User < ActiveRecord::Base
  before_update :update_mailchimp

  def update_mailchimp
    self.changed # => array of changed attributes
    self.changes # => hash of { attribute => [old_value, new_value] }
  end
end

I advice you to read the full documentation of AR Dirty module.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top