meoww-
meoww-

Reputation: 1892

Rails custom routing via Model String Key (instead of id)

I am trying to set up an application where I can route via a String key instead of an id attribute. To illustrate this, please consider the following:

I have a class Foo which inherits from the ActiveRecord::Base and is implemented as follows:

 class Foo < ActiveRecord::Base
 attr_accessible :subject

Subject is a string type which exists in my database.

I have a controller which I implement as follows:

 class SubjectController < ApplicationController

 def index
   #snip
 end

As you can see, the SubjectController inherits from the ApplicationController.

Running rake routes gives me the standard (GET, POST, PUT, DELETE) routes for my subject. This is the expected behavior and I understand this functionality.

I want to know how I can extend the routes.rb file so that I can use a string url in order to access a subject. For example:

Instead of typing in localhost:3000/subject/1, I would like this /:id to resolve when I type in the url: localhost:3000/subject/grumpy-cat-says-hello

  1. What does this implementation look like?
  2. How should I setup my routes.rb file to accommodate this?
  3. How should I configure my application to allow for this type of implementation?

Thank you in advance.

Upvotes: 2

Views: 1156

Answers (1)

Ju Liu
Ju Liu

Reputation: 3999

I've always used https://github.com/FriendlyId/friendly_id for this stuff.

If you prefer something simpler, this will do

class Foo < ActiveRecord::Base
  def to_param
    [id, subject.parameterize].join("-")
  end
end

Then you can access your resource with: localhost:3000/foos/1-grumpy-cat-says-hello Basically, since the name of the resource still starts with a number, it will be converted to a number by Rails and everything will work seamlessly.

This Gist goes in much greater detail about this topic :)

Upvotes: 3

Related Questions