In the last part, I uncovered a problem with my implementation of the Drafts app I’m building with Ruby on Rails. In this post, I’ll sort that out, and also add a fix so that I can use pretty urls.
The problem I have inadvertently built in is this. I’m using a resource called
drafts, but calling what should be another resource called
Fixing the Rails Resources
Rails is quite picky about this, and for good reason. After all, in this case, it is
articles I’m trying to work with, not
drafts. As it turns out,
drafts will most likely become a related resource of
To fix it, all I had to do was create a new controller:
rails g controller articles index show
That now means that I can create a
articles resource in app/config/routes.rb:
Which means that I’m not going to run into problems when it comes to linking to, and displaying an article.
Linking to Articles
index.html.erb I can now alter the display of the articles list to look like this:
<h2>Recent Articles</h2> <table class="table table-bordered"> <% @articles.each do |article| %> <tr> <td><%= link_to article.title, article %></td> </tr> <tr> <td><em>Posted: <%= article.created_at.strftime('%a %d %B %Y - %H:%M') %></em></td> </tr> <% end %> </table>
And the link will automatically point to the
show action in the
articles controller because of the articles resources route – I think.
Fixing the URL’s
http://localhost:3000/articles/1 is alright, I figured there was probably a way to have more descriptive links. It turns out that there is.
I used the FriendlyId gem. Once added to my Gemfile (don’t forget
bundle install) all I had to do to get it working, was add a new field to the database table for articles, called
So in Terminal I did:
rails g migration AddSlugToArticles slug:string
In the resulting migration file a also added an index to the field since it will be used for searching:
class AddSlugToArticles < ActiveRecord::Migration def change add_column :articles, :slug, :string add_index :articles, :slug end end
I picked up that tip from Ryan Bates.
Next, I logged into ActiveAdmin and added a slug for each article in the new field that ActiveAdmin has automatically picked up.
Now everything just works. The links automatically change to use the slug. Clicking one… causes an error of course. I need to create the
show action in the articles controller:
def show @article = Article.find(params[:id]) end
Notice the way we can still use
params[:id]? FriendlyId sorts it out for you. What a great gem that is.
So the implantation problem is fixed, ActiveAdmin is still working, and now we have pretty url’s too. In the next post, I’ll have a go at getting Markdown support working.