Redirect on catching an exception in a method in the model

青春壹個敷衍的年華 提交于 2019-12-22 10:53:29

问题


I am using Authlogic-connect to connect various service providers. There is a method in user.rb

def complete_oauth_transaction
      token = token_class.new(oauth_token_and_secret)
      old_token = token_class.find_by_key_or_token(token.key, token.token)
      token = old_token if old_token

      if has_token?(oauth_provider)
        self.errors.add(:tokens, "you have already created an account using your #{token_class.service_name} account, so it")
      else
        self.access_tokens << token
      end
    end

When a service provider is already added it gives the error as stated in the has_token? method and the page breaks. I need to redirect the app to the same page and flash the error. How do i do this? I have overridden the method in my own user.rb so that I can change the code.


回答1:


Hmm, well you could put a method that handles the error that has_token? throws, and tell your controller to redirect that exact error. something like this in your controller:

rescue_from OauthError::RecordNotFound, :with => :deny_access then you can put



def deny_access
  redirect_to your_view_path, :alert => "Too bad sucker" #some flash message
end

Or you could do something like this in the controller:


if complete_oauth_transaction.errors.present?
  redirect_to your_view_path
else
  # continue on with the normal code here
end

This is how you could generically handle errors. Your exact code will vary, as this is all we have to go off of.



来源:https://stackoverflow.com/questions/4535507/redirect-on-catching-an-exception-in-a-method-in-the-model

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