我尝试在rails 4.2.0 app中设置逻辑,其中一个人必须先确认其用户帐户才能登录site / rails应用。基本上,我有一个注册表单,一个人可以输入一个电子邮件/密码和他们注册。在此过程中,电子邮件将通过确认令牌发送到其地址,该确认令牌应为其提供确认其帐户的链接。我不确定如何使用确认令牌,因此它将DB中的布尔值从false更改为true。我将发布到目前为止已实施的内容。
users_controller.rb
def create
@user = User.new(user_params)
if @user.save
# send confirmation email after user has been created.
@user.send_confirmation
session[:user_id] = @user.id
redirect_to root_url, notice: "Thank you for signing up!"
else
render "new"
end
end
def confirm
@user = User.find_by_confirmation_token!(params[:id])
if @user.update_attributes(confirmed: true)
redirect_to login_path
end
end
confirmation.text.erb
To confirm your account, click the URL below.
<%= user_url(@user.confirmation_token) %>
<%= url_for(controller: 'users', action: 'confirm') %>
If you did not request your account creation, just ignore this email and your account will not be created.
的routes.rb
Rails.application.routes.draw do
resources :articles do
resources :comments
end
get 'resume' => 'resume#index'
get 'signup' => 'users#new'
get 'login' =>'sessions#new'
get 'logout' => 'sessions#destroy'
# the below route led to a rails routing error
# get 'confirm' => 'users/:confirmation_token#confirm'
resources :users
resources :sessions
resources :password_resets
# route to hopefully get confirmation link working :-/
match '/users/:confirmation_token', :to => 'users#confirm', via: [:post, :get]
# test route
match 'users/foo', :to => 'users#foo', via: [:post, :get]
root "articles#index"
# Added below route for correct "resumé" spelling
get 'resumé', :to =>"resume#index"
# get 'about#index'
get 'about' => 'about#index'
get 'contact' => 'contact#contact'
resources :about
resources :contact
match ':controller(/:action(/:id))(.:format)', via: [:post, :get]
答案 0 :(得分:0)
我最终将确认逻辑分离到它自己的控制器,即远离 users_controller.rb 这允许我将以下行添加到我的 routes.rb < / p>
resources :confirmations
允许我编辑 confirmation.text.erb 并在电子邮件中添加以下链接,
<%= edit_confirmation_url(@user.confirmation_token) %>
因此,当一个人收到确认其帐户的电子邮件时,它会路由到确认控制器的编辑操作,编辑操作会调用更新操作,并确认该帐户。控制器如下所示,
confirmations_controller.rb
class ConfirmationsController < ApplicationController
def new
end
def edit
@user = User.find_by_confirmation_token!(params[:id])
update
end
def update
# @user = User.find_by_confirmation_token!(params[:id])
if @user.confirmation_sent_at < 2.hours.ago
redirect_to new_confirmation_path, :alert => "Confirmation has expired."
# elseif @user.update_attributes(params[:user])
elsif @user.update_attributes(confirmed: true)
redirect_to root_url, :notice => "Your account has been confirmed."
else
render :new
end
end
end