I have a use case in which my user wants to be able to create an instance of a model which has several has_many relationships. Easy enough.
However, these has_many relationships will change over time, and any future change should not have an any impact on any existing instances of my model. A little more tricky.
Let’s jump into an example. I have a FleetRoster, which is composed of a list of Trucks. Each truck belongs to a Transporter. I want to create a new FleetRoster by selecting the relevant Trucks. However, as a Truck can change from one Transporter to another, when I create my FleetRoster, I want this Truck-to-Transporter relationship to be captured so that when I generate a document from my FleetRoster it will show the correct relationships at the time of creation.
Here are my models:
class FleetRoster < ActiveRecord::Base serialize :data has_many :fleet_trucks has_many :trucks, :through => :fleet_trucks end class FleetTruck < ActiveRecord::Base belongs_to :fleet_roster belongs_to :truck end class Truck < ActiveRecord::Base belongs_to :transporter end class Transporter < ActiveRecord::Base has_many :trucks end
The key line here is the first line in the FleetRoster model. I’m telling ActiveRecord to serialize the :data column before a save operation, and what this allows us to do is store something like a hash in this column.
Then all we need to do is prior to saving a new instance, gather all the relevant information (Trucks, Transporters etc) including their relationships at the time of processing, and store this information in a normal hash. Next, modify your view to render information from your hash instead. Finally, remove the option to edit these records.
You will then effectively have created immutable records which preserve all the relationship information.
The benefit of doing this instead of generating and saving documents is that should your document design change, you don’t have a whole load of documents using the old layout. After all, we’re only interested in the CONTENT, not the LAYOUT. It also means that everything related to your documents can stay in your database (the content) and your models (the layout and format).