Re: Callbacks vs Observer vs "Just adding to controller action"

kevin cline
Fri, 30 Nov 2007 16:09:42 -0000

On Nov 30, 8:06 am, ebrad
<nisguy_...-/E1597aS9LQAvxtiuMwx3w@public.gmane.org>
wrote:
> 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,

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

  ...