开发者

check if the value of a field changed in a before_update filter

开发者 https://www.devze.com 2022-12-20 22:31 出处:网络
I have a database field where I want to store my password. In a before_create filter in my model I call a encryption function and save from clear text to encrypted text.

I have a database field where I want to store my password. In a before_create filter in my model I call a encryption function and save from clear text to encrypted text.

I want now to use the before_update also for encryption, but only if the value has changed. How can I write a condition for checking if a field val开发者_如何学JAVAue has changed?


If the field is called name then

object.name_changed?

will return true.


Since you usually do not store the password in the model using a field which you would expose to the form, it should be sufficient to only update it unless password.blank? and have the real password in a field "hashed_password" which you won't expose to the form.

Thanks to Ben (see below) for pointing out to additionally protect your encrypted password with attr_protected so it cannot be directly accessed/updated from the form. +1

0

精彩评论

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