ruby-on-rails-3 – Rails设计gem – 通过将其分割到其他模型来自定义默认用户模型

我已经尝试过设计rails gem,并想知道分割它在多个模型中创建的用户模型属性的最佳方法是什么.

现在,我的用户模型如下所示,这是默认的设计行为:

User(id: integer, email: string, encrypted_password: string,
password_salt: string, reset_password_token: string, remember_token:
string, remember_created_at: datetime, sign_in_count: integer,
current_sign_in_at: datetime, last_sign_in_at: datetime,
current_sign_in_ip: string, last_sign_in_ip: string, created_at:
datetime, updated_at: datetime)

我希望在另一个模型中具有以下某些属性,例如:看家狗

sign_in_count, current_sign_in_at, last_sign_in_at,
current_sign_in_ip, last_sign_in_ip

我正在考虑使用委托方法简单地委托他们:

delegate :sign_in_count, :sign_in_count=, ..., :to => :watchdog

有兴趣听听有关此问题的更好解决方案.

谢谢,

塞尔吉奥

最佳答案 您也可以创建自己的关注点,而不必覆盖Devise内部.执行此操作后,仅在模型上扩展Trackable模块.

    module Trackable
      def update_tracked_fields!(request)
        old_current, new_current = watchdog.current_sign_in_at, Time.now.utc
        watchdog.last_sign_in_at     = old_current || new_current
        watchdog.current_sign_in_at  = new_current

        old_current, new_current = self.current_sign_in_ip, request.ip
        watchdog.last_sign_in_ip     = old_current || new_current
        watchdog.current_sign_in_ip  = new_current

        watchdog.sign_in_count ||= 0
        watchdog.sign_in_count += 1

        watchdog.save(:validate => false)
      end
    end

但是不要忘记将record.update_tracked_fields!(warden.request)放在Warden :: Manager.after_set_user块上,就像我们在Devise hook上一样.

点赞