开发者

Unwanted redirection after authentication

We have a form to submit ratings for a certain restaurant in a in our views/restaurants/show.html.erb. We only want logged in users to create new ratings. We put

before_filter :login_required, :only => [ :new, :create ]

(but we also tried only ":create") on top of our RatingsController. If we click the submit button after typing in the rating details we are prompted to log in (which is what we want). After filling in username and password and submitting the login form we get redirected back to e. g. /restaurants/36/ratings, but we want to be redirected back to where we came from - e. g. /restaurants/36/. We tried redirect_to(:back), but this redirects us back to the login form. Also the new rating does not get saved to the database.

Any idea how we can change the redirection and how to make sure the rating gets s开发者_高级运维aved?

Thanks!


Disclaimer: I don't use restful-authentication. (You might look into authlogic if you have a choice -- there's a Railscast about it if you want an intro.) Even so, storing the "back" value in the session should still work out. Here's what I do in my situation:

# app/controllers/application.rb

before_filter :authorize

protected

  # Override in controller classes that should NOT require authentication (such as logging in, by definition)
  def require_login?
    return true
  end

private

  def authorize
    if require_login? && current_user.nil?
      session['return_to'] = request.request_uri
      redirect_to login_url

      return false
    end
  end

# app/controllers/user_sessions_controller.rb

def create
  # [...]

  if @user_session.save
    flash[:notice] = 'Successfully logged in.'

    if session['return_to'].nil?
      redirect_to root_url
    else
      redirect_to session['return_to']
    end
  else
    render :action => 'new'
  end
end

# app/controllers/users_controller.rb

# Just as an example:
def require_login?
  return case action_name
  when 'new'
    false
  when 'create'
    false
  else
    true
  end
end

My application requires almost every action to require authentication, which is why I have require_login? return true. I think you could adjust the session['return_to'] idea to your needs.

I think I got part of this idea from this post: http://www.urubatan.info/2007/10/a-very-simple-login-example-with-rails/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜