Implementing a Tab for the Audit Log Dashboard only Shown to Admin Users
Learn how to update the navigation bar to show the audit log tab when an admin user is accessing the site, including working with the Pundit permission structure helper methods.
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 audit log functionality ready, it's time to build it into the interface.

I think the best way is to add a new tab for audit log, and have a table-driven layout similar to posts. Remember, this tab should be visible only for admin users. So, let's work on this tab first.

Go to _nav.html.erb and add a tab for Audit Log, like this:

<!-- app/views/shared/_nav.html.erb -->

<li class="<%= active?(audit_logs_path) %>">
  <%= link_to "Audit Log", audit_logs_path %>
</li>

Next, let's create a new policy file for our audit logs called audit_log_policy.rb because we need a policy specific to our audit logs. Many parts of this file's code is going to be similar to post_policy.rb, so you can copy the code from that file and make some changes to it. Firstly, change the name of the class to AuditLogPolicy, remove post_approved? method and user_or_admin method and finally, change update? to index? and in this method, return true if the user is an admin. So, the final code should look like this:

# app/policies/audit_log_policy.rb

class AuditLogPolicy < ApplicationPolicy
  def index?
    return true if admin?
  end

  private

    def admin?
      admin_types.include?(user.type)
    end
end

Though this code is fine, it doesn't talk anything about showing a tab. So, to implement that, go to _nav.html.erb again and include an if statement before the audit log display.

<!-- app/views/shared/_nav.html.erb -->

<% if policy(AuditLog).index? %>
  <li class="<%= active?(audit_logs_path) %>">
    <%= link_to "Audit Log", audit_logs_path %>
  </li>
<% end %>

Let's see if it works. If you refresh the browser and if you're logged in as an admin user, you should see this tab.

medium

Now that's working, so let's refactor our code a little. Open the shared folder and create a new partial called _audit_log_tab.html.erb. Inside this new partial, I'm going to move the audit log code from _nav.html.erb.

<!-- app/views/shared/_audit_log_tab.html.erb -->

<li class="<%= active?(audit_logs_path) %>">
  <%= link_to "Audit Log", audit_logs_path %>
</li>

Now, the code in _nav.html.erb should just be:

<!-- app/views/shared/_audit_log_tab.html.erb -->

<%= render 'shared/audit_log_tab' if policy(AuditLog).index? %>

If you're wondering why we didn't build this feature using test driven development, it's because I'm not a huge fan of tests for view files as it is fairly straightforward and can be fragile.

Resources