DEPRECATION WARNING in Rails3 for before_create, before_update, before_save, before_destroy

前端 未结 1 1947
醉梦人生
醉梦人生 2021-02-03 23:02

I just upgraded my application from Rails 2.3 to 3 and I\'m getting some DEPRECATION WARNINGS for my before_create ,update, save, destroy etc.

Does anyone know how ot f

相关标签:
1条回答
  • 2021-02-03 23:55

    The warning you're seeing is Rails 3's attempt to discourage you from overwriting the base before_* and after_* methods. This is similar to how you would have before_filter and other callbacks in your controller.

    What this means is that instead of doing:

    def before_create
      self.username.downcase!
      self.salt = User.make_salt(self.username)
      self.hashed_password = User.hash_with_salt(@password, self.salt)
    end
    

    Rails wants you to do:

    before_create :downcase_username_and_create_password
    
    def downcase_username_and_create_password
      self.username.downcase!
      self.salt = User.make_salt(self.username)
      self.hashed_password = User.hash_with_salt(@password, self.salt)
    end
    

    In this case, you might even split up the two, as there could be a possibility that you'd want to generate a password independently:

    before_create :downcase_username, :create_password
    
    def downcase_username
      self.username.downcase!
    end
    
    def create_password
      self.salt = User.make_salt(self.username)
      self.hashed_password = User.hash_with_salt(@password, self.salt)
    end
    
    0 讨论(0)
提交回复
热议问题