【发布时间】:2017-10-03 15:44:29
【问题描述】:
我正在尝试在 Rails API 应用程序中实现用户帐户。 我有用于注册和登录的用户逻辑,但我的问题是电子邮件链接是 GET 请求,而所需的操作是 POST。我可以像这样在 Postman 中通过 POST 请求手动激活 URL:
http://localhost:3000/users/confirm-request?token=b96be863aced91480a2a
如何通过单击电子邮件中的链接来完成此操作?
我的用户控制器:
class UsersController < ApplicationController
def create
user = User.new(user_params)
if user.save
UserMailer.registration_confirmation(user).deliver
render json: { status: 201 }, status: :created
else
render json: { errors: user.errors.full_messages }, status: :bad_request
end
end
def confirm
token = params[:token].to_s
user = User.find_by(confirmation_token: token)
if user.present? && user.confirmation_token_valid?
user.mark_as_confirmed!
render json: {status: 'User confirmed successfully'}, status: :ok
else
render json: {status: 'Invalid token'}, status: :not_found
end
end
def login
user = User.find_by(email: params[:email].to_s.downcase)
if user && user.authenticate(params[:password])
if user.confirmed_at?
auth_token = JsonWebToken.encode({user_id: user.id})
render json: {auth_token: auth_token}, status: :ok
else
render json: {error: 'Email not verified' }, status: :unauthorized
end
else
render json: {error: 'Invalid username / password'}, status: :unauthorized
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
end
我的路线.rb:
Rails.application.routes.draw do
resources :users, only: :create do
collection do
post 'confirm'
post 'login'
end
end
registration_confirmation.text.erb:
Hi <%= @user.name %>,
Thanks for registering. To confirm your registration click the URL below.
<%= confirm_users_url(@user.confirmation_token) %>
【问题讨论】:
-
AFAIK(据我所知),您不能将链接添加到 POST,因为默认情况下所有链接都是 GET。现在,您可以在 POST 中创建链接,但这已经通过 JS 完成。话虽如此,电子邮件并不真正支持 JS(也许是一些?),因此最好只使用 GET 请求。要回答您的问题:您只需将您的 routes.rb 从
post 'confirm'更改为get 'confirm'
标签: ruby-on-rails