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:
UserSession:
class UserSession < ActiveRecord::Base
belongs_to :user
endUser:
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?
end
endAnd 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 = User.new #=> new user object
u.build_user_session
u.any_delegated_method = 'something' #=> 'something'
u.email = 'some@ema.il' #=> "some@ema.il"
u.save #=>both models User and UserSession are saved
u.any_delegated_method = 'new_value' #=> 'new_value'
u.save #=> 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
u.email = 'new@ema.il' #=> "new@ema.il"
u.save #=> 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)