Possible Duplicate:
making a pretty url via ruby
I have looked around but I can't find an answer. I am either not asking the right question and/or I am not looking in the right place.
I have the following defined:
config/routes.rb
resources :members
members_controller.rb
def show
@member = Member.find(params[:id])
end
As of now when showing a member, the URL is http://myapp.tld/members/1. Let's say the member's name was cooldude. How hard would it be to show http://myapp.tld/members/cooldude or even http://myapp.tld/cooldude if possible?
Thanks for your help.
I recommend friendly_id but if you want to roll a solution of your own, this should get you started:
slugfield to your modelslugfield before savingto_paramin your model to return thesluginstead ofidSetup your model:
Change your finder to:
Note that
find_by_name!(see the bang?) will raise aActiveRecord::RecordNotFoundexception rather than returningnil. In production, this will automatically show a 404 page.In your views, you can use
member_path(@member)which will now return/members/cool-dudeinstead of/members/1.Check out the docs: