I’ve been trying to make my Rails create URLs to show records by using their title instead of their ID in URL such as:
/posts/a-post-about-rockets
Following a tutorial online I did the following:
Because the ID is no longer in the URL, we have to change the code a bit.
class Post < ActiveRecord::Base
before_create :create_slug
def to_param
slug
end
def create_slug
self.slug = self.title.parameterize
end
end
When a post is created, the URL friendly version of the title is stored in the database, in the slug column.
We also have to update the finds to find records using the slug column instead of using the ID.
class ProjectsController < ApplicationController
def show
@project = Project.find_by_slug!(params[:id])
end
end
At this point it seems to work except showing a record, because find_by_slug! doesnt exist yet.
I’m an extreme newb – where should I be defining it?
find_by_foo is not something that you need to define. ActiveRecord will take of it for you, as long as you have a column named “foo”. Adding an exclamation point like you did will cause an exception to be thrown if no record is found, as opposed to returning nil without the exception if you don’t use the exclamation point.
As for your specific issue, you added your slug to Post, but you’re trying to search on Project.