gpt4 book ai didi

ruby-on-rails - ActiveRecord 未更新/保存,但显示该字段已在控制台中修改(db 另有说明)

转载 作者:行者123 更新时间:2023-12-04 06:17:01 25 4
gpt4 key购买 nike

content = Content.find(params[:content_id])
content.body.insert(start_index, span_open)
content.save!
content.body.insert(end_index + span_open.length, span_open)
content.save!

puts "=========================================="
c = Content.find(params[:content_id])
puts c.body

所以以上是我一直在尝试做的事情。很多保存..它应该保存对吗?

在我看到的控制台中

===========================================
le modified text (body attr) here

我将 span 插入到文本中,并且在控制台(上方)中显示 puts 语句中的更改成功。但是当我重新渲染页面时,一切都恢复原状(检查元素显示没有跨度)

我觉得奇怪的一件事是 puts 语句在

之前执行
"Processing NameOfController#action (for ....)" 

所有的数据库调用等等。我向下滚动到 Content.find 所在的位置(它在那里两次,所以这很容易),我看到了这个:

SHOW FIELDS FROM `contents`
Content Load (1.6ms) SELECT * FROM `contents` WHERE (`contents`.`id` = 328)
SQL (0.2ms) BEGIN
SQL (0.1ms) COMMIT
SQL (0.1ms) BEGIN
SQL (0.2ms) COMMIT
CACHE (0.0ms) SELECT * FROM `contents` WHERE (`contents`.`id` = 328)
SQL (0.1ms) BEGIN
SQL (0.1ms) COMMIT

现在,它说它正在从缓存中加载第二个调用...这是怎么回事?自从上次 .find() 以来我已经更改了它?

我正在使用 Ruby on Rails 2.3.8

更新:结合 Dan Seaver 的建议:

  content = Content.uncached_find(params[:content_id])
content.body = content.body.insert(start_index, span_open)
content.save!
content.body = content.body.insert(end_index + span_open.length, span_close)
content.save!
a = content.body
# ActiveRecord::Base.connection.update("
# UPDATE `contents`
# SET body = '#{content.body}'
# WHERE id = #{params[:content_id]}")
puts "=========================================="
content = Content.uncached_find(params[:content_id])
puts (a == content.body).inspect

输出/终端:

==========================================
false

Content Load (1.5ms) SELECT * FROM `contents` WHERE (`contents`.`id` = 351)
SQL (0.1ms) BEGIN
SQL (0.1ms) COMMIT
SQL (0.1ms) BEGIN
SQL (0.2ms) COMMIT
Content Load (0.3ms) SELECT * FROM `contents` WHERE (`contents`.`id` = 351)

最佳答案

Rails SQL Caching的方式有效的是查询缓存在一个 Action 中:

However, it’s important to note that query caches are created at the start of an action and destroyed at the end of that action and thus persist only for the duration of the action. If you’d like to store query results in a more persistent fashion, you can in Rails by using low level caching.

This article描述了如何使用以下内容避免缓存

Update 之前没有使用过uncached,好像是在active record中定义的,所以你必须给内容添加一个类方法,如下所示:

def self.uncached_find(content_id)
uncached do
find(content_id)
end
end

然后使用 Content.uncached_find(params[:content_id]) ( documentation ),您将使用 Content.find

更新 2 我现在看到问题了!!你实际上并没有修改任何东西。 String#insert 返回一个修改后的字符串,它不会原地修改content.body,你需要做如下操作:

content.body = content.body.insert(start_index, span_open)

在你的保存中尝试上面的行,它应该可以工作

关于ruby-on-rails - ActiveRecord 未更新/保存,但显示该字段已在控制台中修改(db 另有说明),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8000660/

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