Rails 3 - Devise redirects to form after sign_in

半腔热情 提交于 2019-12-06 13:17:02

问题


In a blog app I want every user to access a form to post a comment.

When the user submit the comment form he is redirected to the Devise sign_in form if is not logged in.

before_filter :authenticate_user!, :except => [:index, :show, :new]

How could I once the user sign_in, redirect him to the comment form and fill all fields ?

Thanks in advance


回答1:


If you want to take the user to comment form after every sign in, add in ApplicationController:

#after_sign_in_path_for is called by devise
def after_sign_in_path_for(resource_or_scope)
  comment_path...
end

If you want to take user back to the page they were at before sign in, you could save the current controller+action in session and redirect back:

session[:pre_login_controller] = params[:controller]
session[:pre_login_action] = params[:action]

And then :

def after_sign_in_path_for(resource_or_scope)
  if session[:pre_login_controller] && session[:pre_login_action]
    "#{session[:pre_login_controller]}/#{session[:pre_login_action]}"
  else
     some default path -- root url or comment path etc
  end
end



回答2:


There are multiple solutions highlighted on Stack Overflow for redirecting to previous URL after a Devise login.

This is probably the most logical solution, and there is also a solution that includes CanCan (which I recommend using)

Rails: Warden/Devise - How to capture the url before login/failed access

As for the filling in forms, I think a simple solutions would be to restrict the comment box in the first place. Check if user is logged in (I think in Devise it's user_signed_in?) and if user_signed_in? else "You must link_to sign in in order to comment". If you have the comments in an action such as #new, then you could restrict the entire new action through devise. For that, get rid of your :new in the authentification 'except'.



来源:https://stackoverflow.com/questions/5704955/rails-3-devise-redirects-to-form-after-sign-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!