[英]Redirect user to login page in the controllers method if else block - Rails 4, Ruby
I want to be able to redirect a guest user to a Devise signin/login page after he/she clicked some links for 5 times. 我希望能够在访客单击某些链接5次后将访客用户重定向到Devise登录/登录页面。 I counted clicks and I have else block where I am supposed to redirect guest to a sign up page but nothing happens.
我计算了点击次数,但还有其他地方会阻止我将访客重定向到注册页面,但没有任何反应。 Log says:
日志说:
Started GET "/users/sign_in" for 127.0.0.1 at 2014-02-21 14:06:58 +0100
Processing by Devise::SessionsController#new as */*
Rendered /home/.rvm/gems/ruby-2.0.0-preview2/gems/devise-3.2.2/app/views/devise/shared/_links.erb (3.6ms)
Rendered /home/.rvm/gems/ruby-2.0.0-preview2/gems/devise-3.2.2/app/views/devise/sessions/new.html.erb within layouts/application (18.3ms)
Completed 200 OK in 49ms
But I don't get redirected anywhere. 但我不会被重定向到任何地方。 Is there a way to do this?
有没有办法做到这一点?
Controller method count: 控制器方法计数:
def count
user = guest_user
if ( params[:first_link] || params[:second_link] )
user.increment!(:counter)
else
redirect_to new_user_session_url # this is the problem
end
end
Any help would be appreciated. 任何帮助,将不胜感激。
Update: 更新:
function count(link_id) {
$.ajax({
type: 'GET',
format: 'json',
url: '/count/' + link_id,
success: function(data) {
if (data.counter == 5) {
document.location.href = 'new_user_session_path';
}
}
});
return false;
}
And the error I get is: No route matches [GET] "/new_user_session_path" but the route is actually there: new_user_session_path GET /users/sign_in(.:format) devise/sessions#new 我得到的错误是:没有路由与[GET]“ / new_user_session_path”匹配,但实际上存在路由:new_user_session_path GET /users/sign_in(.:format)devise / sessions#new
You are not checking the counter
anywhere, you could do something like this: 您不在任何地方检查
counter
,可以执行以下操作:
def count
user = guest_user
if user.counter == 5 # Assuming that you have counter property on User
user.counter = 0 # reset the counter
redirect_to new_user_session_url **#this is the problem**
else
if ( params[:first_link] || params[:second_link] )
user.increment!(:counter)
end
end
end
BUT As Marek suggested, you should think about resolving this on client side using JavaScript
rather than making server calls. 但是,正如Marek所建议的那样,您应该考虑使用
JavaScript
在客户端解决此问题,而不是进行服务器调用。
Instead of 代替
document.location.href = 'new_user_session_path';
You should have: 你应该有:
document.location.href = '<%= new_user_session_path -%>';
This way, Rails will automatically generate proper URL for you using new_user_session_path
helper. 这样,Rails将使用
new_user_session_path
帮助程序自动为您生成正确的URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.