将用户控制器逻辑移入模型

时间:2015-09-07 09:17:43

标签: ruby-on-rails

我正在使用名为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

1 个答案:

答案 0 :(得分:0)

您可以将代码的update属性部分移动到model,以使控制器代码看起来干净可读:

<强> CONTROLLER

将其称为@user.update_oauth_details(request)(或任何其他名称)

模型用户

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