当未登录用户点击此页面上的“Deja Tu Opinion”按钮时:
...用户被重定向到登录页面,并显示一条消息“您必须先登录或注册才能继续”。我已经做到了——这里没问题。
'Deja Tu Opinion' 按钮指向 new_testimonial_path。但是,如果他们没有登录,他们会被重定向到登录页面。我通过编写“require_login”方法并放入应用程序控制器来实现这一点:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
private
def require_login
if !logged_in?
redirect_to('/user_sessions/new')
flash[:notice] = "Necesitas entrar o salir antes de continuar"
end
end
end
然后我在我的推荐控制器中声明了它:
class TestimonialsController < ApplicationController
before_action :set_testimonial, only: [:show, :edit, :update, :destroy]
# before_action :correct_user, only: [:edit, :update, :destroy]
before_action :require_login, except: [:index, :show]
当他们然后登录时,他们被重定向到 root_path:
class UserSessionsController < ApplicationController
# skip_before_filter :require_login, except: [:destroy]
def new
@user = User.new
end
def create
if @user = login(params[:email], params[:password])
redirect_to root_url, notice: 'Login successful!'
else
flash.now[:alert] = 'Login failed'
render action: 'new'
end
end
def destroy
logout
redirect_to(root_url, notice: 'Logged out!')
end
end
但是......我想要发生的是让他们在这种情况下被引导到 new_testimonial_path,而不仅仅是回到 root_path。
因此,总而言之,一个未登录的用户点击“Deja tu opinion”按钮(意思是“写你自己的推荐信”),因为他们没有登录,所以他们被定向到 new_user_session_path。然后他们登录并被带回root_path,然后他们必须再次向下滚动页面并单击“Deja tu opinion”按钮,然后将他们带到new_testimonial_path。
想要发生的是未登录用户单击“Deja tu opinion”按钮,并且由于他们未登录,因此被定向到 new_user_session_path。然后他们登录并被定向到 new_testimonial_path (因为这是他们首先想要的)。
我使用了 Sorcery gem,我很确定有一种方法可以实现这一点,称为“redirect_back_or_to”,但我只是无法从文档中弄清楚如何使用它。
整个应用的代码在这里(create_testimonials 分支):https ://github.com/Yorkshireman/pamplona_english_teacher2/tree/create_testimonials
巫术的文档: https ://github.com/NoamB/sorcery
希望你能帮忙!