简体   繁体   中英

redirect user to a specific page with rails 3

I use devise and i need redirect a user to specific page if seller_disabled_paypal_permissions != nil from my application_controller.rb

I have this code on my application_controller.rb

class ApplicationController < ActionController::Base
 before_filter :bad_sellers
 #more code
 .
 .
 .
 private
   def bad_sellers
    if user_signed_in?
     redirect_to requirements_to_sell_user_path, :alert => t('.error') if current_user.seller_disabled_paypal_permissions != nil
     return false
    end
   end
end

But I get error:

Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.

How can I do it?

private
   def bad_sellers
    if user_signed_in? && !(current_user.seller_disabled_paypal_permissions.nil?)
     redirect_to root_path, :alert => t('.error')
    end
   end

I've never explicitly returned any value from a before_fiter so that's my first guess.

Your problem is that you've created this behavior on ApplicationController and I am wagering that your root path is also a controller that inherits from ApplicationController therefore its placing you into an infinite redirect loop.

You'll need something like:

before_filter :bad_sellers, :except => [:whatever_your_root_path_action_is]

When you have a conditional redirect, you would want to use return so rails doesn't see any other redirects (not sure how to put it better than that).

as per your example:

def bad_sellers
  if user_signed_in?
    if !current_user.seller_disabled_paypal_permissions.nil?
      return redirect_to root_path, :alert => t('.error')
    end
  end
end

It looks like it may be recursive. Does root_path also call this before filter? You would want to find a way not to call this in that case. Look into skip_before_filter

Also, you don't need to 'return false'.

The fix to the problem:

On applicatio_controller.rb

class ApplicationController < ActionController::Base
 protect_from_forgery
 before_filter :bad_sellers
 #code here
 #code here
 def bad_sellers
  if user_signed_in? && !(current_user.seller_disabled_paypal_permissions.nil?)
   redirect_to requirements_to_sell_user_path(current_user), :alert => t('.error')
  end
 end
end

On users_controllers.rb ( users_controllers is child of application_controller )

class UsersController < ApplicationController
 skip_before_filter :bad_sellers, :only => [:requirements_to_sell] #parent filter on application_controller.rb

 def requirements_to_sell
  #more code
  #more code
 end

end

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