我正在尝试对活动存储文件的删除方法执行 Ajax 请求,这样我的页面就不会重新加载。
我有两个控制器:“project_steps”(我正在使用 wicked gem)和“projects”。
我的观点:project_steps/fourth_step.html.erb
<% if @project.supporting_docs.attached? %>
<div id="remove_file">
<%= render partial: "existing_files", :locals => {project: @project} %>
</div>
<% end %>
我的部分:project_steps/_existing_files.html.erb
<% @project.supporting_docs.each do |file| %>
blah blah
<%= link_to 'Remove', delete_file_attachment_project_url(file.signed_id),
method: :delete, remote: true, class: "btn btn-sm btn-danger" %>
<% end %>
我的项目_控制器:
def delete_file_attachment
file = ActiveStorage::Blob.find_signed(params[:id])
file.attachments.first.purge
respond_to do |format|
format.js
end
end
项目/delete_file_attachment.js.erb:
$('#remove_file').html("<%= j render(partial: 'project_steps/existing_files', :locals =>
{project: @project}) %>")
我的路线:
resources :projects do
member do
delete :delete_file_attachment
end
end
scope 'projects/:project_id' do
resources :project_steps
end
我的错误
ActionView::Template::Error (undefined method `supporting_docs' for nil:NilClass):
3: <strong>You have attached the following files:</strong>
4: </div>
5: <br>
6: <% @project.supporting_docs.each do |file| %>
7: <div class="row">
8: <div class="col">
我的删除工作正常,我明白为什么会出现错误,但我想知道如何让 Ajax 工作以及我做错了什么?很高兴根据需要提供尽可能多的代码!泰。
PS如果有人想提出一个解决方案而不是通过部分你觉得可能会更好!