Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

Rails - Two or more dots in the url

I have a rails app where a route is defined as

get "/:username", to: "profiles#show", as: :show_profile, constraints: UsernameConstraints.new

And UsernameConstraints is defined as

class UsernameConstraints
  #Some code
  def matches?(request)
    request.path.match?(/.*/) 
  end
  #Some code
end

So that usernames can be something like myapp.com/user.name

How do I change this code to accept usernames with two or more dots (myapp.com/something.like.this)? At the moment I can't get rid of the No route matches error.

I tried adding format: true to the route and re-building the username in the controller using the parameters:

myapp.com/something.like.this 

{"username"=>"something", "format"=>"like.this"}

params[:username] = "#{params[:username]}.#{params[:format]}" 

But it’s not a clean solution and also the route does not match any more simple usernames like /username

question from:https://stackoverflow.com/questions/65877179/rails-two-or-more-dots-in-the-url

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
get "/:username", to: "profiles#show", 
                  as: :show_profile, 
                  username: /[^/]+/
Started GET "/foo.bar.baz" for ::1 at 2021-01-25 01:19:18 +0100
Processing by ProfilesController#show as HTML
  Parameters: {"username"=>"foo.bar.baz"}
Hello World!
Completed 204 No Content in 0ms (ActiveRecord: 0.0ms | Allocations: 45)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...