将用户控制器逻辑移动到模型中
问题描述:
我正在使用名为stripe_connect的gem,它是Stripe的Oauth2解决方案。现在目前这个代码工作正常,它是半重复性的,当涉及到将用户控制器逻辑移动到模型中
request.env['omniauth.auth']
但旁边我认为它看起来不错。不过,我希望将此从控制器中移出并放入模型中。但是,我不确定如何进行转换。任何人都可以得到帮助吗?
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
before_action :authenticate_user!
def stripe_connect
@user = current_user
if @user.update_attributes(
provider: request.env['omniauth.auth'].provider,
uid: request.env['omniauth.auth'].uid,
access_code: request.env['omniauth.auth'].credentials.token,
publishable_key: request.env['omniauth.auth'].info.stripe_publishable_key
)
redirect_to rooms_path
set_flash_message(:notice, :success, kind: 'Stripe') if is_navigational_format?
else
session['devise.stripe_connect_data'] = request.env['omniauth.auth']
redirect_to new_user_registration_url
end
end
end
答
您可以移动代码的更新属性部分进行建模,使控制器代码看起来很干净,可读:
控制器
称其为(或任何其他名称)
MODEL(User)
def update_oauth_details(request)
self.update_attributes(
provider: request.env['omniauth.auth'].provider,
uid: request.env['omniauth.auth'].uid,
access_code: request.env['omniauth.auth'].credentials.token,
publishable_key: request.env['omniauth.auth'].info.stripe_publishable_key
)
end