提问人:Benjamin Scharbau 提问时间:11/15/2023 更新时间:11/16/2023 访问量:36
无法销毁 unless 子句中的活动记录 [closed]
Can't destroy active record in an unless clause [closed]
问:
如果只是在我的 Rails 应用程序中出现一个行为,我无法正确解释自己,但仍然想正确理解正在发生的事情。
我有一个ActiveRecord对象,其关联如下has_one
class List < ApplicationRecord
has_one :item
end
另一边有一个协会,像这样belongs_to
class Item < ApplicationRecord
belongs_to :list
end
(类名仅供说明之用,与我现实世界的应用程序不同,所以请不要争辩说只有一个项目的列表没有多大意义)。
我现在想删除现有项目,但只有在检查它是否确实存在之后。
我首先尝试将对象与nil
list.item.destroy unless list.item = nil
但在这里我得到一个错误
ActiveRecord::RecordNotSaved:
Failed to remove the existing associated item. The record failed to save after its foreign key was set to nil.
但是,当我对关联进行 nil 检查时
list.item.destroy unless list.item.nil?
它实际上按预期工作。
谁能向我解释一下那些调用之间有什么区别,为什么一个有效而另一个无效?
答:
1赞
luisiniguezh
11/16/2023
#1
您使用的是赋值而不是比较,正确的方法是:
list.item.destroy unless list.item == nil
尽管鼓励积极逻辑,所以最好是:
list.item.destroy if list.item.present?
评论
=
==