开发者

Enforcing a has_one association

开发者 https://www.devze.com 2023-03-17 05:25 出处:网络
I am using devise but the User model is related to a legacy table and so fine it works perfectly. Now I want to implement the ability to reset passwords, and that enforces having new fields (reset_pa

I am using devise but the User model is related to a legacy table and so fine it works perfectly.

Now I want to implement the ability to reset passwords, and that enforces having new fields (reset_password_token and reset_password_token_at), which I cannot create on the original table.

I decided to use the good old delegate with a has_one relationship. Here's what I did:

class User < LegacyDatabase
  set_table_name 'T_CLIENTS'

  devise :database_authenticatable, :authentication_keys => [:email]
  devise :recoverable

  has_one :user_setting

  delegate :reset_password_token,   :to => :user_setting
  delegate :reset_password_sent_at, :to => :user_setting

  # (...)
end

My problem now is that I need to enforce t开发者_JAVA百科hat all users will have a UserSetting created when I need to access the new fields.

If I was doing it by hand, I could do the UserSetting.find_or_create_by_user_id(...), but before going down that path, I'd like to know if rails provides a way to accomplish this without falling back to manual code.


OK, how ugly is this approach (seems to work):

alias :old_user_setting :user_setting

def user_setting
  old_user_setting || create_user_setting
end
0

精彩评论

暂无评论...
验证码 换一张
取 消