gpt4 book ai didi

ruby-on-rails - 无法在 Rails 中将电子邮件作为 URL 中的参数发送

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:24 24 4
gpt4 key购买 nike

我正在编写一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com