Over the next three episodes we’ll show you a great way to add administration to your website.
Above is a screenshot of an early version of the ASCIIcasts site from before it had the administration functions written for it. There was no way to edit or add episodes except by using
script/console or by manually editing the database. What we’d like to do is to add an admin section to the website so that we can make changes to the episodes through the site.
The ‘old’ way to do this would be to generate a scaffold for the episodes within an admin module.
script/generate scaffold episode "admin/episodes"
This would provide a set of admin pages to allow us to manage our episodes.
This approach works, but it is not ideal as we’re duplicating functionality. We already have a perfectly good page that lists our episodes: the home page of our site. Instead of writing an entirely separate admin section, we could place our administration links inline in the public website. (Of course we’ll only want our admin links to be visible to logged-in administrators!)
Implementing The Admin Links
The short episode summaries in the index page are rendered from within a partial. We’ll edit that partial now to add the edit and destroy links.
<p class="episodeId"><%= episode.episode_id %></p>
<h3><%= link_to episode.title, episode_path(episode.identifier) %></h3>
<p class="summary"><%= episode.summary %></p>
<p class="tagList">Tags: <% episode.tags.each do |tag| %> <%= link_to tag.title, tag_path(tag.title) %> <% end %></p>
<%= link_to "Edit", edit_episode_path(episode) %>
<%= link_to "Destroy", episode_path(episode), :confirm => "Are you sure?", :method => :delete %>
episode partial with the
destroy links added.
At the bottom of the index page we’ll add a link to create a new episode:
<%= link_to “New”, new_episode_path %>
Now our index page has the admin links, but we have two problems. Firstly, the links don’t do anything as we’ve not written the new, edit or destroy actions yet; secondly the links can be viewed by anyone. The first problem is easily solved by writing the appropriate code for the
update etc. actions, and we’ll discuss the second one in the next episode.