首页 > 解决方案 > 在rails中删除操作后返回什么类

问题描述

我正在使用rails-ujs删除一个对象,我的目标是在我删除它之后隐藏那个div和那个obj,我以前做过,但是这次我不能得到它,我想我需要知道发生了什么. 正在查看:

<div class="employee_<%= employee.id %>" 
<%= link_to 'Destroy', employee, method: :delete, remote: true } %>
</div

在 destroy.js.erb 上:

$('div.each-employee-data').find('div.employee_<%= @employee.id %>').hide(); # if i change the id to employee.id i get another error

控制器:

format js

控制台错误:

NoMethodError in Employees#destroy

Showing 
/Desktop/bad/current/app/views/employees/destroy.js.erb where line #1 
raised:
undefined method `id' for nil:NilClass

Rails.root: /Desktop/bad/current

Application Trace
app/views/employees/destroy.js.erb:1:in 
`_app_views_employees_destroy_js_erb__4462192751889852231_70177039108760'

标签: ruby-on-railsrails-ujs

解决方案


一旦你销毁了一个记录 - 你不应该再使用它,它不再有一个id. 对于您的情况,您可以在控制器中删除之前保存 id:

@deleted_employee_id = @employee.id
@employee.destroy
...

在 js 视图中...find('div.employee_<%= @deleted_employee_id %>').hide()...

PS。使用“软删除”也是常见的做法 - 在模型中有一个标志,指示记录是否被“删除”并将其设置为destroy行动,没有实际删除,如果用户想要“撤消”,这很有用。


推荐阅读