Skip to content

Instantly share code, notes, and snippets.

@oojikoo-gist
Created April 15, 2015 17:15
Show Gist options
  • Save oojikoo-gist/c551045e8b8c93958d0d to your computer and use it in GitHub Desktop.
Save oojikoo-gist/c551045e8b8c93958d0d to your computer and use it in GitHub Desktop.
rails: association callbacks
# Association Callbacks
Normal callbacks hook into the life cycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a :before_save callback to cause something to happen just before an object is saved.
Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of a collection. There are four available association callbacks:
## avaliable callbacks
- before_add
- after_add
- before_remove
- after_remove
```
class Customer < ActiveRecord::Base
has_many :orders, before_add: :check_credit_limit
def check_credit_limit(order)
...
end
end
```
```
class Customer < ActiveRecord::Base
has_many :orders,
before_add: [:check_credit_limit, :calculate_shipping_charges]
def check_credit_limit(order)
...
end
def calculate_shipping_charges(order)
...
end
end
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment