Rails 3: GET request with email crops off TLD
-
07-07-2021 - |
题
I am trying to use a controller and action to do a simple check to see if a user account with that email address exists or not.
The controller's action looks like this:
def checkEmail
email = params["email"]
if Account.find_by_email(email).blank?
render :inline=>"true"
else
render :inline=>"false"
end
end
And to test this action, I can go to:
http://localhost:3000/home/checkEmail/email@website.com
When I do so, I can see in the Ruby console the following being queried:
Parameters: {"email"=>"email@website"}
Account Load (0.0ms) SELECT `accounts`.* FROM `accounts` WHERE `accounts`.`email` = 'email@website' LIMIT 1
You can see that the TLD of the email address has been cropped off.
However, when I go to:
http://localhost:3000/home/checkEmail/email@website.co.uk
I get a routing error:
No route matches [GET] "/home/checkEmail/email@website.co.uk"
My routes.rb file looks like this:
Gallery::Application.routes.draw do
#Match home URL
match 'home(/:file)' => "home#index"
match 'home/checkUser/:username' => "home#checkUser"
match 'home/checkEmail/:email' => "home#checkEmail"
root :to=> "home#index"
end
解决方案
Yeah, the default behavior in Rails is to treat a dot (.) in a route as a format specifier, instead of part of the parameter. In order to match the dot as part of the parameter, specify the route like this:
match "/home/checkEmail/:email" => "home#checkEmail", :constraints => { :email=> /[^\/]*/ }
Here's a post that describes the problem and the fix: http://coding-journal.com/rails-3-routing-parameters-with-dots/