gpt4 book ai didi

ruby-on-rails - ActiveRecord 验证失败后如何将内容保存到数据库?

转载 作者:数据小太阳 更新时间:2023-10-29 07:10:15 25 4
gpt4 key购买 nike

基本上我想要做的是在 MyModelLog 表中记录对 MyModel 的操作。这是一些伪代码:

class MyModel < ActiveRecord::Base
validate :something

def something
# test
errors.add(:data, "bug!!")
end
end

我也有一个看起来像这样的模型:

class MyModelLog < ActiveRecord::Base

def self.log_something
self.create(:log => "something happened")
end

end

为了记录我尝试:

  • MyModel

    something方法中添加MyModelLog.log_something
  • MyModel

    after_validation 回调上调用 MyModelLog.log_something

在这两种情况下,创建都会在验证失败时回滚,因为它在验证事务中。当然我也想在验证失败时记录。我真的不想登录文件或数据库以外的其他地方,因为我需要日志条目与其他模型的关系以及执行请求的能力。

我有哪些选择?

最佳答案

嵌套事务似乎在 MySQL 中有效。

这是我在新生成的 Rails(使用 MySQL)项目上尝试的:

./script/generate model Event title:string --skip-timestamps --skip-fixture

./script/generate model EventLog error_message:text --skip-fixture

class Event < ActiveRecord::Base
validates_presence_of :title
after_validation_on_create :log_errors

def log_errors
EventLog.log_error(self) if errors.on(:title).present?
end
end

class EventLog < ActiveRecord::Base
def self.log_error(event)
connection.execute('BEGIN') # If I do transaction do then it doesn't work.
create :error_message => event.errors.on(:title)
connection.execute('COMMIT')
end
end

# And then in script/console:
>> Event.new.save
=> false
>> EventLog.all
=> [#<EventLog id: 1, error_message: "can't be blank", created_at: "2010-10-22 13:17:41", updated_at: "2010-10-22 13:17:41">]
>> Event.all
=> []

也许我过度简化了它,或者遗漏了一些要点。

关于ruby-on-rails - ActiveRecord 验证失败后如何将内容保存到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3881089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com