Generating the Audit Log Feature Using the Resource Generator
Walk through the process for generating the audit log component, including the basic routes and tests.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Now that we have our plan in place, let's begin by creating a database table called AuditLog that references to the user table, and has status, start_date and end_date as attributes.

The command for this is:

rails g resource AuditLog user:references status:integer start_date:date end_date:date

One thing we'll have to do now is to update our migration file. Remember, we want our status field to have a default value of 0. As for start_date, we'll handle it in our model file.

So, our migration file should look like this:

# db/migrate/20160729184625_create_audit_logs.rb

class CreateAuditLogs < ActiveRecord::Migration
  def change
    create_table :audit_logs do |t|
      t.references :user, index: true, foreign_key: true
      t.integer :status, default: 0
      t.date :start_date
      t.date :end_date

      t.timestamps null: false
    end
  end
end

Next, let's run bundle exec db:migrate, to update the schema file.

Now, establish the link between user and audit logs. Open user.rb model file and include

# app/models/user.rb

has_many  :audit_logs

Then, open the audit_log.rb file to verify that it already has the relational connection, like this:

# app/models/audit_log.rb

class AuditLog < ActiveRecord::Base
  belongs_to :user
end

Now, open rails console in sandbox mode, and create an audit log. We only need the user_id to create a record successfully, below is a sample script you can run to create to test this functionality:

AuditLog.create!(user_id: User.last.id)

We can confirm that this works by running the database query:

User.last.audit_logs

And you'll see that this returns the right value too.

Everything looks great, let's take a break and move onto the next guide when you're ready.

Resources