简体   繁体   中英

Rails 3 - Devise redirects to form after sign_in

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

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

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'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM