2016-12-28 66 views
2

我正在使用Rails设计。将before_filter authenticate_user!应用于控制器非常神奇,几乎可以提供我正在寻找的确切重定向解决方案。不过! - 我更喜欢当点击被authenticate_user!阻止的链接时,用户将被重定向到new_user_registration_path(注册),而不是new_user_session_path(登录)。Rails devise before_filter authenticate_user!指南注册路径而不是登录路径

有没有一种方法可以轻松定制设计,以允许这样做?

回答

2

UPDATE

我们可以使用store_location_for存储提供的位置在登录后,将用户重定向。


在你application_controller.rb添加

protected 

def authenticate_user! 
    unless user_signed_in? 
    store_location_for(:user, request.url) 
    redirect_to new_user_registration_url 
    end 
end 

而在你的控制器您可以添加:

before_action :authenticate_user!, :unless => :devise_controller? # This prevent the infinite redirects. 

上面的代码将为您的问题中提到的特定控制器执行技巧,并重定向用户注册页面而不是登录页面。如果您只想在视图中的特定链接上使用,则可以查看我在EDIT下发布的代码。

编辑


你可以简单的检查,如果!current_user当链接的用户点击,它会被重定向到注册页面。下面的这段代码肯定会将用户返回到上一页。你可以把下面的代码到你的意见,并使用if else还有:

<% if !current_user %> 
    <%= link_to 'Register', new_user_registration_path %> 
<% end %> 

注意 的before_filter语法用Rails 5.0弃用,并将在滑轨被删除5.1

+0

这会强制正确注册页面,但无法将用户重定向到其原始目的地他现成的'before_filter:authenticate_user!'确实如此 – Robinson

+0

这是真的!请检查编辑的版本 – Blackcoat77

+1

我更新了我的代码,以便您可以对用户进行身份验证,并将他/她重定向到注册页面而不是特定控制器上的登录页面。您想在成功注册后将它们重定向到上一页吗?如果你有一些代码请分享,以便我们可以帮助你。 – Blackcoat77

1

在你application_controller.rb文件:

before_filter :authenticate_user 

def authenticate_user 
    redirect_to new_user_registration_url unless user_signed_in? 
end