如何选择凡在阵列ID的Rails的ActiveRecord无异常阵列、如何选择、异常、ID

2023-09-09 22:03:06 作者:明天的阳光美吗

当我有数组ids的,像

When I have array of ids, like

ids = [2,3,5]

和我执行

Comment.find(ids)

一切工作正常。但是,当有一个不存在的id,我得到一个异常。出现这种情况generaly时,我得到了一些匹配滤波器和比我做这样的事情

everything works fine. But when there is id that doesn't exist, I get an exception. This occurs generaly when I get list of IDs that match some filter and than I do something like

current_user.comments.find(ids)

这一次,我可能有一个有效的评论的ID,但不属于特定用户,所以它不存在,我得到一个异常。

This time I may have a valid comment ID, which however does not belong to given User, so it is not found and I get an exception.

我已经试过找到(:所有,IDS),但它返回的所有记录

I've tried find(:all, ids), but it returns all of the records.

现在我能做到这一点的唯一方法是

The only way I can do it now is

current_user.comments.select { |c| ids.include?(c.id) }

不过,在我看来,像超级低效率的解决方案。

But that seems to me like super inefficient solution.

有没有更好的方式来选择的在阵列ID 的而对不存在的记录得到异常?

Is there better way to select ID in Array without getting exception on non-existing record?

推荐答案

如果它只是避免了异常你担心的find_all_by ..系列函数工作而不会抛出异常。

If it is just avoiding the exception you are worried about, the "find_all_by.." family of functions works without throwing exceptions.

Comment.find_all_by_id([2, 3, 5])

即使一些id的不存在将工作。该作品在

will work even if some of the ids don't exist. This works in the

user.comments.find_all_by_id(potentially_nonexistent_ids)

情况下也是如此。

case as well.