Skip to content
lyang edited this page Mar 19, 2013 · 2 revisions

Associations

Most of the models has associated other models.

has_one/belongs_to association

For example, a BraintreeRails::CreditCard belongs to a customer. It has a customer_id attribute, which will be used to load customer object

credit_card = BraintreeRails::CreditCard.find('credit_card_id') # Vaulted card
credit_card.customer # => lazy loaded and cached upon the first call

credit_card = BraintreeRails::CreditCard.new # unsaved card
credit_card.customer # => nil

has_many association

  1. Loading

    Some of braintree_ruby models has eager loaded collection associations, others don't. For example, Braintree::Customer object eager loads credit cards:

    Braintree::Customer.find('customer_id') # This eager loads all the credit cards this customer has

    BraintreeRails will leverage that to build the association. In addition, when there's no eager loaded association, BraintreeRails will add association through api search if available.

    For example, Braintree::Customer object in braintree_ruby does not have a transactions collection. BraintreeRails added that association by

    customer.transactions         # Returns a lazy loaded and cached collection through Braintree::Transaction.search,
    customer.transactions.each {} # However, this could potentially be a very slow api request, use with caution.
  2. Scoped creation

    Another benefit of association is it provides a scoped creation just like ActiveRecord. For example,

    #create a transaction for this customer using his/her default credit card
    customer.transactions.create(:amount => '10.00') # This will not trigger the slow api search request
  3. Scoped find

    Find will be scoped in the lazy loaded collections

    #find given transaction in the lazy loaded collection
    customer.transactions.find('transactionid')
Clone this wiki locally