Domanda

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.

È stato utile?

Soluzione

I recommend friendly_id but if you want to roll a solution of your own, this should get you started:

  1. Add a slug field to your model
  2. Set the slug field before saving
  3. Override to_param in your model to return the slug instead of id

Setup your model:

# member.rb
before_save do
  self.slug = name.parameterize
end

def to_param
  slug
end

Change your finder to:

# members_controller.rb
def show
  @member = Member.find_by_name!(params[:id])
end

Note that find_by_name! (see the bang?) will raise a ActiveRecord::RecordNotFound exception rather than returning nil. In production, this will automatically show a 404 page.

In your views, you can use member_path(@member) which will now return /members/cool-dude instead of /members/1.

Check out the docs:

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top