Richard
Richard

Reputation: 948

How to keep columns of the same data updated in multiple tables Rails

I have a table PaymentAccount that keeps track of payment accounts. I have instance methods in the PaymentAccount that returns if the payment account is "ready" e.g. account.is_payment_ready?.

Every time updates are made to the these records, I would like to update another column payment_ready in a table called Profile with the corresponding boolean value. Instead of querying for account.is_payment_ready? whenever profiles are retrieved, I would like to be able to just do profile.payment_ready to reduce the # of DB queries.

Note PaymentAccount and Profile would have a one-to-one association.

My first instinct is to have an after_commit hook in the PaymentAccount model as such:

class PaymentAccount < ActiveRecord::Base
    after_commit :update_profile

    def is_payment_ready?
       if ready
          return true # if ready
       else
          return false # if not ready
       end
    end 

    def update_profile
       self.profile.payment_ready = is_payment_ready?
       self.profile.save
    end
end

Would this be the correct approach? Assume that both Profile and PaymentAccount always exists for a given User.

Upvotes: 0

Views: 340

Answers (1)

mackshkatz
mackshkatz

Reputation: 881

You would be better off using a before_save rather than an after_commit in the case that something went wrong in the saving of the Profile, you wouldn't want the two records to get out of sync when the PaymentAccount saved but the Profile rolledback for whatever reason. Not to mention, another added benefit is that both updates will happen in the same db transaction.

Also, you get the method #ready? for free from ActiveRecord, so you might as well use that rather than writing a method that is essentially just an alias.

So something like:

class PaymentAccount < ActiveRecord::Base
  before_save :update_profile

  private

  def update_profile
    profile.payment_ready = ready?
    profile.save
  end
end

Upvotes: 1

Related Questions