Rails3中的DEPRECATION警告,用于before_create,before_update,before_save,before_destroy

时间:2010-09-22 03:35:50

标签: ruby-on-rails ruby-on-rails-3

我刚刚将我的应用程序从Rails 2.3升级到3,我得到了一些 我的before_create,更新,保存,销毁等的弃权警告

有谁知道如何解决这个问题?

这些是我的警告:

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的一个例子:

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

1 个答案:

答案 0 :(得分:63)

您看到的警告是Rails 3试图阻止您覆盖基本的before_*after_*方法。这类似于控制器中before_filter和其他回调的方式。

这意味着不是做:

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希望你这样做:

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

在这种情况下,您甚至可能将两者分开,因为您可能希望独立生成密码:

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