Alex Smith
Alex Smith

Reputation: 385

Username URLs that aren't case sensitive

I have an application where users set usernames, and their profile URL is matched to their username similar to Twitter. The issue I'm running into is case sensitivity. I'm down casing usernames before they save to the database, but I'm still getting the issue. Here's how I'm matching the URL's in routes

  match "/:id" => "users#show", via: :get

Upvotes: 1

Views: 104

Answers (1)

mohameddiaa27
mohameddiaa27

Reputation: 3597

Assuming that you store it in the column called username.

In you Users Controller show action. You need to down case both the username column and the username from the params.

So you need to change:

@user = User.find_by_username(params[:id])

To be:

@user = User.find(:first, :conditions => ["lower(username) = ?", params[:id].downcase])

For a cleaner approach you may change params[:id] to be params[:username] to avoid confusion.

Your route will be:

match "/:username" => "users#show", via: :get

Finding the user will be using params[:username]

@user = User.find(:first, :conditions => ["lower(username) = ?", params[:username].downcase])

Upvotes: 4

Related Questions