当我有一些id,比如
ids = [2,3,5]
Run Code Online (Sandbox Code Playgroud)
我表演
Comment.find(ids)
Run Code Online (Sandbox Code Playgroud)
一切正常.但是当存在不存在的id时,我会得到一个例外.当我获得与某些过滤器匹配的ID列表时,通常会发生这种情况
current_user.comments.find(ids)
Run Code Online (Sandbox Code Playgroud)
这次我可能有一个有效的评论ID,但不属于给定的用户,所以找不到它,我得到一个例外.
我试过了find(:all, ids),但它返回了所有记录.
我现在能做到的唯一方法是
current_user.comments.select { |c| ids.include?(c.id) }
Run Code Online (Sandbox Code Playgroud)
但在我看来,这似乎是超低效的解决方案.
有没有更好的方法在Array中选择ID而不会在不存在的记录上获得异常?