覆盖设计注册#create而不复制/粘贴逻辑

时间:2012-07-09 18:24:18

标签: ruby-on-rails inheritance devise

所以,我的应用程序中有自己的注册控制器,为新注册的用户添加角色分配

class RegistrationsController < Devise::RegistrationsController
  def create
    build_resource
    resource.role = Role.find_by_name('registered')
    if resource.save
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_navigational_format?
        sign_in(resource_name, resource)
        respond_with resource, :location => after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
        expire_session_data_after_sign_in!
        respond_with resource, :location => after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      respond_with resource
    end
  end
end

有没有更简洁的方法来为此方法添加功能?我宁愿不必将设计代码复制/粘贴到我的方法中,以保持逻辑与我的逻辑分离。

我想我可以在模型级别处理它,并进行回调,但我不确定最佳做法是什么

1 个答案:

答案 0 :(得分:0)

结束只是将其重构为回调

class User < ActiveRecord::Base
  before_create :set_role

  private
  def set_role
    if self.role.nil?
      self.role = Role.find_by_name('registered')
    end
  end
end

更清洁。完全摆脱了客户设计控制器。