Let’s say you’re implementing rails app for a snowboard rental store.
A given snowboard can be in one of 3 states:
- away for maintenance
- available at store X
- on loan to customer Y
The company needs to be able to view a rental history for
- a particular snowboard
- a particular customer
The rental history needs to include temporal data (e.g. Sally rented snowboard 0123 from Dec. 1, 2009 to Dec. 3 2009).
How would you design your model? Would you have a snowboard table with 4 columns (id, state, customer, store), and copy rows from this table, along with a timestamp, to a snowboard_history table every time the state changes?
Thanks!
(Note: I’m not actually trying to implement a rental store; this was just the simplest analogue I could think of.)
I would use a pair of plugins to get the job done. Which would use four models. Snowboard, Store, User and Audit.
acts_as_state_machine and acts_as_audited
AASM simplifies the state transitions. While auditing creates the history you want.
The code for Store and User is trivial and acts_as_audited will handle the audits model.
Assuming your customer is the current_user during the controller action when state changes that’s all you need.
To get a snowboard history:
To get a customer’s rental history:
You might want to create a helper method to shape a customer’s history into something more useful. Maybe something like his: