ruby-on-rails - 在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'
解决方案
一旦你销毁了一个记录 - 你不应该再使用它,它不再有一个id
. 对于您的情况,您可以在控制器中删除之前保存 id:
@deleted_employee_id = @employee.id
@employee.destroy
...
在 js 视图中...find('div.employee_<%= @deleted_employee_id %>').hide()...
PS。使用“软删除”也是常见的做法 - 在模型中有一个标志,指示记录是否被“删除”并将其设置为destroy
行动,没有实际删除,如果用户想要“撤消”,这很有用。
推荐阅读
- angularjs - AngularJS Component: How to avoid watchers for unused bindings
- dart - 我可以有一个简单地获取 Dart2 中的对象属性的 lambda 表达式吗?
- php - PHP如何避免在每个请求上加载源文件?
- java - 将 spark 驱动程序日志重定向到控制台而不是 stderr 文件
- javascript - Is there a way to select options page and press submit to transfer the info into the selected option page
- swift - 在文本中设置后未调用 UILabel didSet 属性文本:didSet
- r - Ifelse with multiple conditions in sapply function
- angular - router.url does not change it's content when page is changed
- flutter - 如何在 MapBoxMapController 中使用 SymbolOptions 添加标记
- r - 从矩阵计算调整后的 p 值,同时在 R 中保留矩阵维度