Callbacks vs Observer vs "Just adding to controller action"

I am setting up auditing for my app where views, updates, and deletes
are recorded in my Audits table to track the life cycle of an employee
record. I’ve read how great callbacks and observers are, but there
isn’t a way to ‘callback’ for simply viewing a page. The simplest
solution just seems to be manually creating the audit in my show
action, like this:

def show
@employee = Employee.find(params[:id])
Audit.create(
:user => Goldberg.user.name,
:time => Time.now,
:action => ‘Viewed’,
:employee_id => @employee.id
)
end

This works, I’m just wondering if there is a better approach.

On Nov 30, 8:06 am, ebrad [email protected] wrote:

  :user => Goldberg.user.name,
  :time => Time.now,

Rename the time column to ‘created_at’ and RAILS will automatically
set it.

  :action => 'Viewed',
  :employee_id => @employee.id
)

end

This works, I’m just wondering if there is a better approach.

Use before_filter:

class EmployeeController < ApplicationController
before_filter :audit, :only => [ :show, :update, :delete]

def audit
@employee = Employee.find(params[:id]) # hope you have some
authorization check somewhere
Audit.create(:user => …,
:action => params[:action],
:employee_id => params[:id])
end

“Rename the time column to ‘created_at’ and RAILS will automatically
set it.”

  • Geesh I should know that by now.

“# hope you have some authorization check somewhere”

  • if you mean user authentication, then yes.

very nice! thanks Kevin!