devinross
devinross

Reputation: 2816

Ruby on rails: URL from ids to names/titles etc

I created model objects of from generating a scaffold, but now I want to instead of linking to
/:controller/:id (/objectname/1) to /:controller/:title (/objectname/new_blog_post). How do I do this so that links will correct link to the title and not id?

I want to go from:

/:controller/:id 

to

/:controller/:name 

Upvotes: 2

Views: 1135

Answers (4)

Yeameen
Yeameen

Reputation: 833

Use friendly_id.

BTW, generating url isn't working for me. I had written my own to the model

def to_param
  self.friendly_id
end

Upvotes: 0

nitecoder
nitecoder

Reputation: 5486

Use to param

class User < ActiveRecord::Base

  def to_param
    name.blank? ? id : name
  end

end

Or look into a plugin, acts_as_sluggable and friendly_id are ones I know of.

EDIT: Oh yes and as mentioned make sure whatever you use is unique.

EDIT:

it would work like:

class UsersController < ActionController::Base

  def index
    @users = User.all
  end

end

In view:

<% @users.each do |user| %>
  <%= link_to user.name, user_path(@user.id) %>
<% end %>

And if the that users name is John then it will render /users/John after you click that link

Upvotes: 4

theIV
theIV

Reputation: 25794

You will need to change a few things:

You'll have to pass the title attribute to any paths/urls when you do stuff like link_to e.g.

post_path(@post)

will become

post_path(@post.title)

You'll also have to update your finds to look for posts by title, as opposed to id e.g.

@post = Post.find(params[:id])

will become

@post = Post.find_by_title(params[:title])

That should get you started :). You'll obviously want to slug the title and validate the uniqueness of the title as well.

EDIT: After reading Robert Elwell's answer, maybe I misunderstood the question. Do you already have a route like you described for a specific object, or are you doing this with the 'basic' routes? If the latter, you're much better off writing a custom route like Robert suggests, and then doing some of the stuff I suggested.

Upvotes: 1

Robert Elwell
Robert Elwell

Reputation: 6668

Write a custom route.

Upvotes: 0

Related Questions