2017-02-23 51 views
0

我想重定向用戶基於他們用於sign_in的參數,但我沒有看到辦法。從/users/sign_in/?demo=car重定向用戶基於sign_in參數

用戶:: SessionsController <設計:: SessionsController

def create 
super 
# get the params 
if params[:demo] == car 
    # redirect_to where_ever 
end 
end 

顯然,這是行不通的

用戶的跡象。

正確的重定向:

ApplicationController中<的ActionController :: Base的

def after_sign_in_path_for(resource) 
# I must have params[:demo] here. How? 
if params[:demo] == car 
    # go elsewhere 
else 
    request.env['omniauth.origin'] || stored_location_for(resource) || root_path 
end 
end 

一個很長的路將更新用戶與PARAMS列,然後在after_sign_in_path_for我檢查current_user列中params然後重定向。如果用戶來自原始網址,我將該列更新爲""。浪費時間吧?

+0

您可以隱藏的輸入添加到您的登錄表單,並填寫與'PARAMS值:演示]'。提交表單(登錄)後,該值將從'params'訪問。 –

+0

用戶登錄後,我仍然需要該參數。我想我可能需要更新用戶模型以執行我想要的操作。 – Sylar

+0

我已經提出了將參數轉發到'after_sign_in_path_for'方法的方法。然後,您可以將其保存在數據庫中或存儲在會話中。這取決於你的情況;) –

回答

-1

做一個動作之前設置@redir。如果你需要堅持beetwen頁面重定向,存儲在您的會話

class ApplicationController < ActionController::Base 

    before_action :set_redir, if: -> { params[:redir].present? } 

    def set_redir 
    @redir = CGI.unescape(params[:redir]) 
    session[:redir] = @redir 
    end 

    def after_sign_in_path_for(resource) 
    session[:redir] || request.env['omniauth.origin'] || stored_location_for(resource) || root_path 
    end 

end 

會議形式

<%= form_for(resource, :as => resource_name, :url => session_path(resource_name, redir: CGI.escape("http://someurl")), html: {role: 'form'}) do |f| %> 
0

基本上我不得不把代碼從設計的寶石,create複製,到我的。

def create 
    # Do not use super! 
    url = params[:redir] 
    self.resource = warden.authenticate!(auth_options) 

    if url 
    return # my destination 
    end 

    # Continue if no param 
    set_flash_message!(:notice, :signed_in) 
    sign_in(resource_name, resource) 
    yield resource if block_given? 
    respond_with resource, location: after_sign_in_path_for(resource) 

# Alternatively, I could have pass after_sign_in_path_for another param, url 
# then get it in ApplicationController < ActionController::Base 
end 

瀏覽:

# /users/sessions/new.html.erb 
<%= form_for(resource, as: resource_name, url: session_path(resource_name, redir: params[:redirect_uri])) do |f| %>