Ruby on Rails: Showing Member's Name Instead of ID in Show [duplicate]
-
07-07-2021 - |
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.
Soluzione
I recommend friendly_id but if you want to roll a solution of your own, this should get you started:
- Add a
slug
field to your model - Set the
slug
field before saving - Override
to_param
in your model to return theslug
instead ofid
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:
- http://apidock.com/rails/ActiveRecord/Integration/to_param
- http://apidock.com/rails/ActiveRecord/Base (section on dynamic attribute-based finders)