Rails Devise宝石 - 通过在其他模型中分割来自定义默认用户模型 [英] Rails Devise gem - customizing default User model by splitting it across other models

查看:127
本文介绍了Rails Devise宝石 - 通过在其他模型中分割来自定义默认用户模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了devise rails gem,并且想知道分割多个模型中创建的用户模型属性的最佳方法。

I have tried the devise rails gem, and was wondering what the best way would be to split the user model attributes it creates across multiple models.

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

For now, my user model looks as follows, which is the default devise behaviour:


用户(id:integer,email:string,encrypted_pa​​ssword: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:字符串,created_at:
datetime,updated_at:datetime)

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)

我想在另一个模型中有一些属性,例如看门狗

I would like to have some of the attributes below in another model, e.g. Watchdog


sign_in_count,current_sign_in_at,last_sign_in_at,
current_sign_in_ip,last_sign_in_ip

sign_in_count, current_sign_in_at, last_sign_in_at, current_sign_in_ip, last_sign_in_ip

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

I was considering of simple delegating them using the delegate method:

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

有兴趣听到有关这个问题的更好的解决方案。

Would be interested in hearing about better solutions to this problem.

谢谢,

Sergio

推荐答案

您也可以创建自己的关注,而不必重写Devise内部组件。在这样做之后,只需在模型上扩展可追踪模块

You can also create your own concern that does the same without having to override Devise internals. After doing that, only extend Trackable module on your model.

    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

But don't forget to put record.update_tracked_fields!(warden.request) on the Warden::Manager.after_set_user block as we do on Devise hook.

这篇关于Rails Devise宝石 - 通过在其他模型中分割来自定义默认用户模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆