implementing user tracking (logging) in Rails 3

Posted by seth.vargo on Stack Overflow See other posts from Stack Overflow or by seth.vargo
Published on 2011-01-02T00:45:24Z Indexed on 2011/01/02 0:54 UTC
Read the original article Hit count: 134

Hi, I'm creating a Rails application in which logging individual user actions is vital. Every time a user clicks a url, I want to log the action along with all parameters. Here is my current implementation:

class CreateActivityLogs < ActiveRecord::Migration
  create_table :activity_logs do |t|
    t.references :user
    t.string :ip_address
    t.string :referring_url
    t.string :current_url
    t.text :params
    t.text :action

    t.timestamps
  end
end

 

class ActivityLog < ActiveRecord::Base
  belongs_to :user
end

In a controller, I'd like to be able to do something like the following:

...
ActivityLog::log @user.id, params, 'did foo with bar'
...

I'd like to have the ActivityLog::log method automatically get the IP address, referring url, and current url (I know how to do this already) and create a new record in the table.

So, my questions are:

  1. How do I do this? How do I use ActivityLog without having to create an instance everytime I want to log?
  2. Is this the best way? Some people have argued for a flat-file log for this kind of logging - however, I want admins to be able to see a user's activity in the backend as well, so I thought a database solution may be better?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about logging