gpt4 book ai didi

ruby-on-rails - update_attributes() vs. update_all () & on deleted object

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:01 24 4
gpt4 key购买 nike

我正在尝试更新对象的属性,但我尝试更新的对象通常已不存在。

例如:我正在对 CSV 文件进行后处理以获取属性:

array.each do |a|
player = Player.find_by_grepo_id(a[:grepo_id])
player.update_attributes(a)
end

当找不到玩家时会抛出错误。

我从以前的经验中学到的:

ActiveRecord::Base.find always throws an exception if it does not find a record, this is intentional. I should only use find if I'm absolutely expect to have whatever it is I'm looking for. If I'm rending a show action and can't find the article, I should rescue that exception and render a 404 (Not found) instead of redirecting to index (technically).

If I want to find something by it's id attribute without forcing an exception, I should use the dynamic finder find_by_id (In my case find_by_grepo_id) which will return false if it doesn't find a record with that id.

但是在运行包含上述代码的任务时我得到

NoMethodError: undefined method `update_attributes' for nil:NilClass

那是因为具有该特定 ID 的玩家已不存在。如果我将 update_attributes 调用包装在 .present? 方法中,它就可以工作。

我错过了什么? find_by_id 方法不应该抛出错误并跳过它吗?

最佳答案

如果你想在一个电话而不是两个电话中完成,你可以使用 update_all像这样的方法:

Player.where(:grepo_id => a[:grepo_id]).update_all(a)

这将导致以下 SQL:

UPDATE players SET ... = ..., ... = ... WHERE players.grepo_id = ...

如果 grepo_id 不存在也有效:不会更新任何内容。但是请注意,这只是运行 SQL; 模型上的任何验证或回调都将被忽略

关于ruby-on-rails - update_attributes() vs. update_all () & on deleted object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23676751/

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