如何毫无例外地选择Array Rails ActiveRecord中的ID [英] How to select where ID in Array Rails ActiveRecord without exception

查看:18
本文介绍了如何毫无例外地选择Array Rails ActiveRecord中的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有一个 id 数组时,比如

When I have array of ids, like

ids = [2,3,5]

我表演

Comment.find(ids)

一切正常.但是当有不存在的 id 时,我得到一个异常.这通常发生在我获得与某个过滤器匹配的 ID 列表并且比我执行类似的操作时

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.

我试过find(:all, 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)

情况也是如此.

Comment.where(id: [2, 3, 5])

这篇关于如何毫无例外地选择Array Rails ActiveRecord中的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆