-
Notifications
You must be signed in to change notification settings - Fork 22
Associations
Most of the models has associated other models.
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
-
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 bycustomer.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.
-
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
-
Scoped find
Find will be scoped in the lazy loaded collections
#find given transaction in the lazy loaded collection customer.transactions.find('transactionid')