2

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.

1 Answer 1

3

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

Just installed the gem and am getting it all setup. Thanks a ton! Ultra fast response too!! Thanks, Ju Liu!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.