BigRedEd
BigRedEd

Reputation: 97

Rails routing with hyphenated name in path

Im having trouble with some routing due to a user with a hyphenated last name.

My route reads

    get '/team/:first_name-:last_name', to: 'home#employee', as: :employee

For something like "/john-smith" this would obviously work fine, but for an employee with a hyphenated last name such as "Sarah Jane-Smith" that results in "/sarah-jane-smith."

Rails is splitting on the second hyphen, which throws an error as that name doesnt exist.

    SELECT  "employees".* FROM "employees" WHERE (first_name = 'sarah-jane' AND last_name = 'smith')

Is there a simple way to change the route interpretation without having to overhaul my routing for employees?

Thanks in advance.

Upvotes: 0

Views: 304

Answers (1)

user3723506
user3723506

Reputation:

One way I can think of accomplishing this is by doing something like this:

# routes.rb
get '/team/:full_name', to: 'home#employee', as: :employee

And then you can use regex to split the full_name

# home_controller.rb
class HomeController
  private

  def name
    # The regex below assumes that first name can't have hyphens.
    match_data = params[:full_name].match(/([^-]*)-(.*-?.*)/) 
    {
      first_name: match_data[1],
      second_name: match_data[2]
    }
  end
end

Upvotes: 1

Related Questions