1

当未登录用户点击此页面上的“Deja Tu Opinion”按钮时:

https://github.com/Yorkshireman/pamplona_english_teacher2/blob/create_testimonials/app/views/static_pages/home.html.erb

...用户被重定向到登录页面,并显示一条消息“您必须先登录或注册才能继续”。我已经做到了——这里没问题。

'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

希望你能帮忙!

4

1 回答 1

4

解决了:

Sorcery 有自己的方法,称为 require_login,所以我的 require_login 方法似乎阻止了 redirect_back_or_to 方法正常运行。因此,我只是删除了我的 require_login 方法。

当在 before_filter 中触发了 redirect_back_or_to 方法(或 'before_action' - 相同的东西),Sorcery 调用它的另一个本机方法:not_authenticated。它的默认操作似乎是将您定向到您的 root_path。您可以在您的应用程序控制器中覆盖它(只需在私有部分中编写一个名为“not_authenticated”的方法并告诉它要做什么(在我的情况下,“redirect_to new_user_session”)。

这些改变达到了预期的效果。

这里有一些很棒的信息: http ://railscasts.com/episodes/283-authentication-with-sorcery?view=asciicast

于 2015-02-19T02:37:53.220 回答