简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM