3

Railsのフレンドリーなリダイレクトに関連するほとんどすべての投稿を読みましたが、Deviseで認証した後、ユーザーを前のアクションにリダイレクトする方法がわからないようです。

これが私がやりたいことです。

  1. ログインしていないユーザーが「投票」をクリックする
  2. 「before_filter:authenticate_user!」が原因で、ユーザーはログインページに移動します。(私はここまで得ました)
  3. ユーザーがログインした後、「after_sign_in_path_for(resource)」はユーザーを前のアクション(投票)にリダイレクトします。
  4. 投票アクションがキャストされ、ユーザーが投票ボタンをクリックした元のページにリダイレクトされます。(「request.referer」は、ユーザーがすでにサインインしている場合にこれを行いますが、この場合、ユーザーはログインページを通過する必要があるため、request.refererは機能しません。)

*「ページ」だけでなく、前の「アクション」にリダイレクトしたいことに注意してください。つまり、ユーザーがログインした後、目的のアクションがすでに実行されている必要があります。

これが私のコードです。

class MissionsController < ApplicationController
  before_filter :store_location
  before_filter :authenticate_user!, :except => [:show, :index] 

  def vote_for_mission
    @mission = Mission.find(params[:id])
    if @mission.voted_by?(current_user) 
      redirect_to request.referer, alert: 'You already voted on this mission.'
    else
      @mission.increment!(:karma)
      @mission.active = true
      @mission.real_author.increment!(:userpoints) unless @mission.real_author.blank?

      current_user.vote_for(@mission)
      redirect_to request.referer, notice: 'Your vote was successfully recorded.'
    end
  end
end

そして私のアプリケーションコントローラーでは、

class ApplicationController < ActionController::Base

  protect_from_forgery                                                                                                       

  def after_sign_in_path_for(resource)
    sign_in_url = "http://localhost:3000/users/sign_in"                                     
    if (request.referer == sign_in_url)
        session[:user_return_to] || env['omniauth.origin'] || request.env['omniauth.origin']  || stored_location_for(resource) || root_path      
    else
      request.referer
    end
  end

  private
  def store_location
    session[:user_return_to] = request.referer
  end

私の主な問題は、前のページがサインインページであるため、ユーザーがログインする必要があるときに、vote_for_missionアクション内の「request.referer」が意図しない場所に移動することだと思います。どういうわけか、ユーザーが投票をクリックしたページをFOOとして保存したい->投票アクションをBARとして保存->サインインページにリダイレクト->ユーザーがログインしたときにBARにリダイレクト-> BARアクションを実行した後、FOOにリダイレクト。

助けてくれてありがとう!

4

1 に答える 1

4

私が一般的に行うことは、次のように ApplicationController 内にメソッドを含めることです。

def remember_location
  session[:back_paths] ||= []
  unless session[:back_paths].last == request.fullpath
    session[:back_paths] << request.fullpath
  end

  # make sure that the array doesn't bloat too much
  session[:back_paths] = session[:back_paths][-10..-1]
end

def back
  session[:back_paths] ||= []
  session[:back_paths].pop || :back
end

次に、任意のアクション(あなたの場合はログインハンドラー)で、次のことができます

redirect_to back # notice, there is no symbol

そして、ジャンプして戻ることができるようにしたいすべてのアクションで、呼び出すだけです

remember_location

これが役立つことを願っています。

于 2012-07-09T10:52:23.893 に答える