简体   繁体   中英

Access to old association inside Rails/ActiveRecord callback

In my Rails callback I have something like this:

private
def update_points
  if user_id_changed?
    user_was = User.find(user_id_was)
    user_was.points -= points_was
    user_was.save
    user.points += points
    user.save
  end
end

Is that the proper way to do this with user_was ? I initially just assumed user_was was already defined (or could be defined on the spot) because user_id_was existed.

It's not clear to me from the context what exactly you're doing (maybe the 2nd points is supposed to be points_was ?). For mildly improved clarity, depending on who you ask, and with fewer lines:

...
  user_was = User.find(user_id_was)
  user_was.update_column :points, user_was.points - points_was
  user.update_column     :points, user.points     + points
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM