Rails3 中的 before_create、before_update、before_save、before_destroy 弃用警告 [英] DEPRECATION WARNING in Rails3 for before_create, before_update, before_save, before_destroy
问题描述
我刚刚将我的应用程序从 Rails 2.3 升级到 3 并且我得到了一些我的 before_create、update、save、destroy 等的弃用警告
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 fix the issue?
这些是我的警告:
DEPRECATION WARNING: Base#before_create has been deprecated, please use Base.before_create :method instead. (called from /Users/macmini/qna/app/models/user.rb:32)
DEPRECATION WARNING: Base#before_update has been deprecated, please use Base.before_update :method instead. (called from /Users/macmini/qna/app/models/user.rb:40)
DEPRECATION WARNING: Base#after_save has been deprecated, please use Base.after_save :method instead. (called from /Users/macmini/qna/app/models/user.rb:50)
DEPRECATION WARNING: Base#before_destroy has been deprecated, please use Base.before_destroy :method instead. (called from /Users/macmini/qna/app/models/user.rb:56)
before_create 的一个例子:
Just one example for the before_create :
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 3 试图阻止您覆盖基础 before_*
和 after_*代码> 方法.这类似于您在控制器中使用
before_filter
和其他回调的方式.
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.
这意味着,而不是做:
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 想让你做的:
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
这篇关于Rails3 中的 before_create、before_update、before_save、before_destroy 弃用警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!