G_Man
G_Man

Reputation: 1343

Custom URL Routing in Ruby on Rails

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.

Upvotes: 0

Views: 644

Answers (2)

Ramfjord
Ramfjord

Reputation: 949

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

Upvotes: 0

iouri
iouri

Reputation: 2929

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.

Upvotes: 3

Related Questions