In my rails application I currently have a load of users who each have a registered user id.
If I go in to my users index and click on a users show page I get the following example header.
localhost:3000/users/3
Now I don't like this as it easily allows people to skip through users in the header.
How would I go about doing the following so that it shows the user.username field instead e.g.
localhost:3000/users/adamwest
You can define a to_param
method on the User model.
class User
...
def to_param
name
end
...
end
Then every generated URLs will have name
instead of id
as a user identifier.
sid = User.new :name => 'sid'
user_path(sid) #=> "/users/sid"
Of course, in the controller, you have to find user by name.
class UsersController
...
def show
@user = User.find_by_name(params[:id])
end
...
end
I also suggest you to take a look at friendly_id gem.
FriendlyId is the “Swiss Army bulldozer” of slugging and permalink plugins for ActiveRecord. It allows you to create pretty URL’s and work with human-friendly strings as if they were numeric ids for ActiveRecord models.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With