2017-02-23 50 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| %>