加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 为什么before_save不会被调用ActiveRecord模型

发布时间:2020-12-16 22:29:52 所属栏目:百科 来源:网络整理
导读:当我使用IRB创建一个新的模型实例并保存时,没有什么打印到控制台,我得到一个“ActiveRecord :: StatementInvalid:Mysql :: Error:Column’user_id’不能为空”的错误,所以我假设before_save不是被叫我不知道为什么.我甚至尝试使用before_save过滤器.这是我
当我使用IRB创建一个新的模型实例并保存时,没有什么打印到控制台,我得到一个“ActiveRecord :: StatementInvalid:Mysql :: Error:Column’user_id’不能为空”的错误,所以我假设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,: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 documtation,before_save在验证之后发生.在你的情况下,验证将失败,并且永远不会调用before_save.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读