首页 > 解决方案 > 如何从 ruby​​ on rails 应用程序中查询 UPDATE 表?

问题描述

在我Document.last.files.first.purge从控制台使用 rails c 进行测试时,第一个文件被删除,但 rails c 也会自动对文档调用 UPDATE 查询。但是当我从我的应用程序中对文件调用 purge 时,我可以看到在 rails 服务器中只启动了 DELETE 查询。(这会导致一堆问题,比如服务器试图加载不存在的 blob,所以我认为在对表进行更改后更新表非常重要。)我的问题是如何从 ruby​​ 复制这个 UPDATE 查询?谢谢!

Rails 服务器的预期结果 doc= Document.last

来自 Rails 服务器的真实结果

删除文件的代码:

控制器(documents_controller.rb)

def delete_file_attachment
    @file = ActiveStorage::Blob.find_signed(params[:id]).purge
end

查看 (_form.html.erb)

<div class="files">
    <% @document.files.each do |file| %>
      <%= link_to file.filename, delete_file_attachment_document_url(file.signed_id), method: :delete, data: { confirm: 'Are you sure?' }%>
    <% end %>
  </div>

模型(document.rb)

class Document < ApplicationRecord
  has_many_attached :files
end

标签: ruby-on-railsrubysqlite

解决方案


尝试在表单上使用 where 子句,并使用 update_all() 为该特定事件运行 SQL 查询。看看这样的东西是否适用于您的数据库 - >

Document.where(conditions).limit(1).update_all(changes) # => 1

这是 Active Record 关系中有关 update_all() 的一些文档 https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-update_all


推荐阅读