ruby-on-rails - 为什么我的 ActiveRecord 模型没有调用 before_save?

标签 ruby-on-rails validation activerecord callback

当我使用 IRB 创建一个新的模型实例并保存时,没有任何内容打印到控制台,并且我收到一个“ActiveRecord::StatementInvalid: Mysql::Error: Column 'user_id' cannot be null”错误,所以我假设 before_save 不是被调用。我不明白为什么。我什至尝试过使用 before_save 过滤器。这是我的代码:

require 'secure_resource/secure_resource_encryption'

class Database < ActiveRecord::Base
  belongs_to :username_encryption, :class_name => "Encryption", :foreign_key => :username_encryption_id
  belongs_to :password_encryption, :class_name => "Encryption", :foreign_key => :password_encryption_id

  # Virtual attribute to retrieve the decrypted username.
  def username
    if self.username_encryption.nil?
      return nil
    end

    begin
      return self.username_encryption.encryption
    rescue SecureResourceError
      raise SecureResourceError
    end
  end

  # Provides a way to reset the username.
  def username=(username)
    if self.username_encryption.nil?
      self.username_encryption = Encryption.new
      self.username_encryption.encryption = username
    end
  end

  # Virtual attribute to retrieve the decrypted password.
  def password
    if password_encryption.nil?
      return nil
    end

    begin
      return password_encryption.encryption
    rescue SecureResourceError
      raise SecureResourceError
    end
  end

  # Provides a way to reset the password.
  def password=(password)
    if self.password_encryption.nil?
      self.password_encryption = Encryption.new
      self.password_encryption.encryption = password
    end
  end

  def before_save
    p 'ZZZZZZZZZZZZZZZ'
    p self.user_id.to_s + ' ZZZZZZ'
    p 'ZZZZZZZZZZZZZZZ'
    self.username_encryption.user_id = self.user_id
    self.username_encryption.save
    self.username_encryption_id = self.username_encryption.id

    self.password_encryption.user_id = self.user_id
    self.password_encryption.save
    self.password_encryption_id = self.password_encryption.id
  end
end

最佳答案

如您所见 in the documentation , before_save验证后发生。在您的情况下,验证将失败并且 before_save永远不会被调用。

由于回调的目标是在验证发生之前将对象设置为有效状态,因此请尝试 before_validation打回来。

关于ruby-on-rails - 为什么我的 ActiveRecord 模型没有调用 before_save?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6310343/

相关文章:

ruby-on-rails - rails : Retrieve the latest record from multiple associated models

ruby-on-rails - Rails Chartkick Gem 加载图表时出错,找不到适配器

jquery - 使用 jquery 一次验证所有表单元素

ruby-on-rails - Rails - 如何获取当前更新记录的 ID(使用 "update_all")?

ruby-on-rails - rails 3.0: ActionController::Base render()

ruby-on-rails - 为什么 application.rb 在 Rails 4.1 和 4.0 之间不同

validation - HTTP POST 中用于数据验证的 HTTP 状态代码和响应主体

unit-testing - 将 validates_uniqueness_of 添加到模型中会导致功能测试失败

ruby - 带有 Ruby 脚本的 ActiveRecord,没有 Rails,连接池超时

ruby-on-rails - rails 4 : how to access an attribute of an ActiveRecord_Relation-Object?