gpt4 book ai didi

ruby-on-rails - 如果记录存在,Rails 如何改进?

转载 作者:太空宇宙 更新时间:2023-11-03 18:21:11 24 4
gpt4 key购买 nike

我有这个模型:

class Device < ActiveRecord::Base
has_many :events

def last_event
events.last
end
end

如您所见,我有一个方法可以获取设备的最后一个事件。现在,在设备模型的其他地方我有这个方法:

def place
self.last_event.place
end

现在,如果我在这个设备的事件中没有任何记录,我会得到一个错误“undefined method ‘place’ for nil:NilClass”。

所以我补充说:

def place
self.last_event.place if self.last_event.present?
end

这种模式在整个应用程序中不断重复,我不得不添加“if self.last_event.present?”所以它也不会在其他地方崩溃。

我确信一定有更好的方法来处理这种事情,而不需要检查 last_event 是否到处都存在?

有什么建议吗?

谢谢,

最佳答案

try 方法(ActiveSupport 的补充)恰好允许这样做。如果在 nil 对象上调用,它也只会返回 nil。因此,以下两行是等价的:

self.last_event.try(:place)
# equivalent to
self.last_event.place if self.last_event

关于ruby-on-rails - 如果记录存在,Rails 如何改进?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18175642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com