Unable to send email as parameter in URL in Rails

早过忘川 提交于 2020-12-13 11:42:10

问题


I am writing an API to find users by email_id.

I am getting an error while sending the email as a parameter.

Routes.rb:

Rails.application.routes.draw do
  namespace :api do
    resources :users, only: [:show, :index] , param: :email
  end
end

When I am sending the email as a parameter then I got an error. The URL is http://localhost:3000/api/users/test@abc.com:

ActiveRecord::RecordNotFound in Api::UsersController#show
Couldn't find User with 'id'={:email=>"test@abc"}

This is my routes path:

api_users_url   GET     /api/users(.:format)            api/users#index
api_user_url    GET     /api/users/:email(.:format)     api/users#show

回答1:


In your email there is a dot ., like @gmail.com. This dot is a problem.

By default, dynamic segments in Rails Routes do not accept dots.

That's why the result will be:

{
  "sender"=>"emai@gmail",
  "format"=>"com"
}

Instead of

{
  "sender"=>"emai@gmail.com"
}

Solution:

In your routes.rb:

get 'message/:sender', to: 'main#message_sent', constraints: { sender: /[^\/]+/} , as: 'message_sent'

The important part is constraints: { sender: /[^\/]+/}, which let's you pass a dot through the url parameter.




回答2:


ActiveRecord::RecordNotFound in Api::UsersController#show
Couldn't find User with 'id'={:email=>"test@abc"}

You should change your show action to below

def show 
  resource = User.find_by(email: params[:email])
  render :json => resource.as_json 
end

By default find takes id, so you should use find_by

OR

You can use where

def show 
  resource = User.where(email: params[:email]).first 
  render :json => resource.as_json 
end



回答3:


You are passing a hash with the key email, and in the controller you are finding the user by id. This is the wrong way to pass the email in URLs like this:

api_user_url    GET     /api/users/:email(.:format)     api/users#show

This is insecure. You have to make routes with a post request for your action and pass the parameter "email": "test@abc" there. Then comes your action. Find the user by email instead of id like this:

@user= User.find_by_email(params[:email])


来源:https://stackoverflow.com/questions/35363017/unable-to-send-email-as-parameter-in-url-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!