Q:

Ruby/Rails - Implicitly create a parent record when creating a child record?

Ok this is a bit unusual, but I have a series of data collection forms that save data to their respective models. What I want to do is auto insert a common parent (activity/event log - separate model) record that will be common to each form. (All forms will save an implicit record in this model, before saving the child record). So the save sequence needs to be as follows:
1) On each detail form capture user input
 2) Create a new parent record containing summary info (User ID, Record Type, Timestamp)
 3) Capture the new Parent PK value for insertion (as a Foreign Key) into the detail record
 4) Populate the detail record with user input data and the FK data, then save
 5) Commit (or Rollback)
How can I do this - where are the hooks for something like this? Obviously I need to override some default bahaviour in Rails to do this - has anyone seen any examples that they can share? 
TIA,
Brendan
P.S. Before you think this is a bass ackwards approach , I need to handle the use case where an activity/significant event occurs, but the underlying detail info is unavailable.
(This is likely to arise with externally imported data when only the parent will get created). Right now I'm primarily interested in exploring a Rails solution to this.

A:

There are several ways to achieve this, depending on How you want it.

  before_save filter in your child record model,

class YourModel < ActiveRecord::Base
  before_save :create_parent

  def create_parent
    #do something here

  end

end

 Active Record Observers ( follows a observer pattern ) 
This goes in your environment.rb file

  config.active_record.observers = :yourmodel_observer

create a yourmodel_observer.rb file
and code 

  class YourModelObserver  < ActiveRecord::Observer

    def after_save(object)

    end

    def after_update(object)

    end
  end

