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

Rails中为Attachment类型invoice字段添加created_at值的问题

问题解决:发票上传日期显示问题

核心原因

你使用的Paperclip附件gem在执行t.attachment :invoice时,默认仅会给cases表生成以下字段:

  • invoice_file_name
  • invoice_content_type
  • invoice_file_size
  • invoice_updated_at

并不包含invoice_created_at字段,所以调用<%= @case.invoice.created_at %>自然会返回null。

解决方案

方案1:直接使用现有字段(最简单)

如果不需要区分「首次上传发票」和「更新发票」的时间,直接用invoice_updated_at即可——首次上传时这个字段的值就是上传时间,只有替换发票时才会更新。

在视图里可以这样写:

<%= @case.invoice_updated_at %>

或者通过Paperclip附件对象访问:

<%= @case.invoice.updated_at %>

方案2:添加专用的invoice_created_at字段

如果必须单独记录首次上传时间,需要给cases表新增该字段:

  1. 生成新迁移文件:
rails generate migration AddInvoiceCreatedAtToCases invoice_created_at:datetime
  1. 执行迁移:
rails db:migrate
  1. 在Case模型中添加回调,确保首次上传时自动设置invoice_created_at:
class Case < ApplicationRecord
  has_attached_file :invoice
  # 其他验证或配置代码...

  before_save :set_invoice_created_at, if: -> { invoice_updated_at_changed? && invoice_created_at.nil? }

  private

  def set_invoice_created_at
    self.invoice_created_at = invoice_updated_at
  end
end
  1. 之后在视图里即可调用:
<%= @case.invoice_created_at %>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:20:34