You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails统计附件记录报错PG::UndefinedColumn的解决方法

解决方法

当你用Paperclip的t.attachment :invoice时,Rails会在cases表生成invoice_file_name、invoice_content_type、invoice_file_size、invoice_updated_at这些字段,并没有invoice_id字段,所以你原来的Case.where.not(invoice: nil)会被错误解析成查询invoice_id IS NOT NULL,导致报错。

正确的统计方式有两种:

  • 直接查询Paperclip生成的字段:
    在视图里使用:

    All the Invoice (<%= Case.where.not(invoice_file_name: nil).count %>)</h3>
    

    因为有附件上传时,invoice_file_name会被赋值,无附件则为nil,以此判断是否存在invoice附件。

  • 给模型添加scope(推荐,代码更易维护):
    在app/models/case.rb中添加:

    scope :with_invoice, -> { where.not(invoice_file_name: nil) }
    

    然后视图里调用:

    All the Invoice (<%= Case.with_invoice.count %>)</h3>
    

内容的提问来源于stack exchange,提问作者nour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 21:05:00