ruby-on-rails - Rails ActiveRecord find array of ids, but some are not found
问题描述
I am trying to find a model by an array of ids like so:
Model.find [1,2,3]
but let's say only two of these models exist (the model with id of 2 was deleted):
#<Model id: 1>
#<Model id: 3>
I get an error like this:
#<ActiveRecord::RecordNotFound: Couldn't find all Models with 'id': (1, 2, 3) (found 2 results, but was looking for 3).>
Is it possible to catch this error and determine which of the models were not present?
say i'm in my controller:
def index
@models = Model.find params.require(:model_ids)
rescue ActiveRecord::RecordNotFound => e
e.full_message
???
end
I'd like to, in the ???
line, run some code on the exception e
that will return 2
, letting me know what of the models was not found, so I can re-run the query without it while noting which ones weren't found.
解决方案
Wrong method. .find
should be used to find specific records when you want the code to raise ActiveRecord::RecordNotFound
. This is done to ensure that the record exists and avoid nil errors. Typically this is used to trigger a 404 response without repeating the same boilerplate:
def show
@record = Record.find_by(id: params[:id])
unless @record
render file: 'public/404.html', status: :not_found
end
end
Use .find_by(id: id)
if you don't want the code to raise.
To fetch multiple records use where:
models = Model.where(id: [1,2,3])
If you want to determine which of those ids don't exist use an array diff:
bad_ids = [1,2,3] - models.ids
推荐阅读
- azure - 使用 Azure B2C 登录时如何在自定义页面中嵌入登录控件
- php - 重定向后我的 CI 会话被破坏
- mysql - 如何将特定的 SELECT 命令与 UPDATE - SQL 结合使用
- database - 在 JSP 中以表格式发布基于 servlet 的数据库查询结果
- python - 如果输入参数在 Django 模板中无效,如何抛出异常
- c++ - 编译系统软件或应用软件
- javascript - Javascript - 需要重复功能
- java - 使用 wait() 和 notify() VS 信号量在不同上下文中创建的 java 线程间通信哪个更好
- c - 如何知道从哪里获取 ac 程序中使用的头文件?
- javascript - 是否可以在 Blade 模板文件中创建 Vue 单文件组件?