Topic: Devise gem and delegate attributes update

Hello. To keep my User model clean I decide to move all Devise columns except email and encrypted_password to the UserSession model. To realize this I use "delegate :attribute". My models below:

class UserSession < ActiveRecord::Base
  belongs_to :user


class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,  :lockable, :timeoutable, #:confirmable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one :user_session
  delegate :reset_password_token, :reset_password_token=,
           :reset_password_sent_at, :reset_password_sent_at=,
           :remember_created_at, :remember_created_at=,
           :sign_in_count, :sign_in_count=,
           :current_sign_in_at, :current_sign_in_at=,
           :last_sign_in_at, :last_sign_in_at=,
           :current_sign_in_ip, :current_sign_in_ip=,
           :last_sign_in_ip, :last_sign_in_ip=,
           :confirmation_token, :confirmation_token=,
           :confirmed_at, :confirmed_at=,
           :confirmation_sent_at, :confirmation_sent_at=,
           :unconfirmed_email, :unconfirmed_email=,
           :failed_attempts, :failed_attempts=,
           :unlock_token, :unlock_token=,
           :locked_at, :locked_at=,
           :to => :user_session

  attr_accessible :email, :password, :password_confirmation, :remember_me

  before_save :build_session_model

  def build_session_model
    build_user_session if self.user_session.nil?

And this works just fine except the UserSession records are keep initial data and don't update it, and I find  a reason. I'll show it by simple example:

u = #=> new user object
u.any_delegated_method = 'something' #=> 'something' = '' #=> "" #=>both models User and UserSession are saved
u.any_delegated_method = 'new_value' #=> 'new_value' #=> returns TRUE, but doesn't update UserSession! despite the fact 1 attribute was changed
#but if I try to change any User attribute it saves User table as expected = '' #=> "" #=> User updated, UserSession - still not (u.any_delegated_method return 'new_value', but in fact database contain 'something')

Thats why my records are not ever updated... If i change "build_session_model" User method by deleting "if self.user_session.nil?" it will build a new db row on each save action and I see, that the new values are actually coming at each save action. So how do I need to build callback to update the records correctly? Thanks for any advise.

Last edited by ArcaneRain (2012-02-10 07:49:02)

Re: Devise gem and delegate attributes update

resolve this by adding after_save scope with saving the connected model