0

I am currently learning ruby on rails with 3.0

I have created a post table with a column called friendly

Instead of using /post/:id I want to use /post/:friendly

meaning a URL will look like /post/post-title instead of /post/1

I have the controller framed properly with this code.

def show
  @post = Post.find(params[:friendly])

  respond_to do |format|
    format.html
    format.json { render :json => @post }
  end
end

But I am not sure how to change routes.rb to implement this change.

Right now it just says

resources :post

Thanks in advance for your help.

3
  • Why are you trying to do this? What advantage do you gain from calling your id column friendly? Commented Sep 18, 2012 at 0:00
  • I updated the post to explain better I want the URL to look like /post/post-title instead of /post/1 Commented Sep 18, 2012 at 0:09
  • This is commonly done for SEO and overall better user experience. Commented Sep 18, 2012 at 3:38

2 Answers 2

3

You can use to_param method on the model http://apidock.com/rails/ActiveRecord/Base/to_param

If you keep object ID inside of the friendly, ex 1-some-name, 2-some-other-name you will not have to do anything else. Rails will strip id from the string and will use it to find your object. If you don't, you will have to change your controllers to use find_by_friendly(params[:id]) instead of find(params[:id])

Another alternative is to use a gem like https://github.com/norman/friendly_id to accomplish this.

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

Comments

0

If you want to change the format of the id variable on find, you can change the route as follows

resources :post, :except => find do
  # Change the find to accept an id that's alphanumeric, but you can change 
  # this regex to whatever you need.
  get 'find', :on => :member, :constraints => { :id => /[a-zA-Z]*/ }
end

then, to get the post in posts#find, you need to do

Post.find_by_friendly(Params[:id])

One problem is that this will break the helper paths - eg post_path(@post) will need to become post_path(:id => @post.friendly)

http://guides.rubyonrails.org/routing.html#http-verb-constraints

Comments

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.