我正在编写一个 API 以通过 email_id
查找用户。
我在发送电子邮件作为参数时遇到错误。
路线.rb:
Rails.application.routes.draw do
namespace :api do
resources :users, only: [:show, :index] , param: :email
end
end
当我将电子邮件作为参数发送时,出现错误。网址是 http://localhost:3000/api/users/test@abc.com :
ActiveRecord::RecordNotFound in Api::UsersController#show
Couldn't find User with 'id'={:email=>"test@abc"}
这是我的路线路径:
api_users_url GET /api/users(.:format) api/users#index
api_user_url GET /api/users/:email(.:format) api/users#show
最佳答案
在您的电子邮件中有一个点 .
,例如 @gmail.com
。这个点是个问题。
默认情况下,Rails 路由中的动态段不接受点。
这就是为什么结果会是:
{
"sender"=>"emai@gmail",
"format"=>"com"
}
代替
{
"sender"=>"emai@gmail.com"
}
解决方案:
在你的routes.rb
中:
get 'message/:sender', to: 'main#message_sent', constraints: { sender: /[^\/]+/} , as: 'message_sent'
重要的部分是 constraints: { sender:/[^\/]+/}
,它让您通过 url 参数传递一个点。
关于ruby-on-rails - 无法在 Rails 中将电子邮件作为 URL 中的参数发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35363017/