如何用Jsonb查询GoodJob中指定ReminderMailer和event_id的延迟邮件
在GoodJob中通过Jsonb字段查询并删除指定延迟邮件
我在Ruby on Rails项目中使用GoodJob发送延迟邮件,当活动取消时,需要找到关联的邮件任务并删除,但对Jsonb查询不熟悉,不知道怎么写正确的语句。需要通过ReminderMailer和event_id来定位目标任务,以下是serialized_params的结构示例:
{ "job_id": "9522f8a0-7eca-4682-a6e8-ef8771e5b86e", "locale": "en", "priority": null, "timezone": "Mountain Time (US & Canada)", "arguments": [ "ReminderMailer", "inspection_created", "deliver_now", { "args": [], "params": { "event_id": 2480, "recipient": [ "jesselasalle@mailer.com", "Jesse" ], "_aj_symbol_keys": [ "event_id", "recipient" ] }, "_aj_ruby2_keywords": [ "params", "args" ] } ], "job_class": "ActionMailer::MailDeliveryJob", "executions": 0, "queue_name": "default", "enqueued_at": "2026-05-12T14:02:41.494322527Z", "scheduled_at": "2026-05-13T18:00:00.000000000Z", "provider_job_id": null, "exception_executions": {}, "_good_job": { "id": "9522f8a0-7eca-4682-a6e8-ef8771e5b86e", "queue_name": "default", "priority": 0, "scheduled_at": "2026-05-13 12:00:00 -0600", "performed_at": null, "finished_at": null, "error": null, "created_at": "2026-05-12 08:02:41 -0600", "updated_at": "2026-05-12 08:02:41 -0600", "active_job_id": "9522f8a0-7eca-4682-a6e8-ef8771e5b86e", "concurrency_key": null, "cron_key": null, "retried_good_job_id": null, "cron_at": null, "batch_id": null, "batch_callback_id": null, "is_discrete": null, "executions_count": null, "job_class": "ActionMailer::MailDeliveryJob", "error_event": null, "labels": null, "locked_by_id": null, "locked_at": null, "lock_type": null } }
我试过下面的代码,但没有查到任何结果:
GoodJob::Job.where("serialized_params->arguments->>0 = ?", "ReminderMailer")
解决方案
1. 基础PostgreSQL Jsonb查询写法
需要同时匹配arguments数组第一个元素为ReminderMailer,以及第四个元素中嵌套的params.event_id,正确的查询语句如下:
# 查询指定任务 target_jobs = GoodJob::Job.where( "serialized_params->'arguments'->>0 = ? AND serialized_params->'arguments'->3->'params'->>'event_id' = ?", "ReminderMailer", event_id.to_s ) # 删除这些任务 target_jobs.destroy_all
语法说明:
serialized_params->'arguments':取出serialized_params中的arguments数组->>0:将数组第一个元素转为字符串,匹配ReminderMailer->3:定位到数组第四个元素(索引从0开始),也就是包含params的哈希对象->'params'->>'event_id':取出params里的event_id并转为字符串,注意要把数字类型的event_id转为字符串后再对比,避免类型不匹配
2. Rails 6+ 简化Jsonb查询写法
如果使用Rails 6及以上版本,可以用更直观的包含查询语法:
# 查询并删除 GoodJob::Job.where("serialized_params @> ?", { arguments: [ "ReminderMailer", nil, nil, { params: { event_id: event_id } } ] }.to_json).destroy_all
语法说明:
@>是PostgreSQL Jsonb的包含操作符,只要serialized_params中的arguments数组包含指定的结构(不需要完全匹配所有元素),就会被匹配到- 前两个
nil是占位符,对应arguments数组的第二、第三个元素(邮件方法名和deliver_now),我们不需要关心这两个值,只需要确保第一个元素和第四个元素的params.event_id匹配即可
内容的提问来源于stack exchange,提问作者darkstarohio
相关产品推荐
相关产品推荐

