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

查看:16
本文介绍了如何在Array Rails ActiveRecord中选择where 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.

我现在唯一能做的就是

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中选择where ID无一例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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