【问题标题】:Override Paperclip:Attachment method覆盖回形针:附件方法
【发布时间】:2016-03-08 18:41:13
【问题描述】:

我需要在上传附件时访问 url,因此我必须定义 after_flush_writes 方法,就像这里建议的 https://github.com/thoughtbot/paperclip/issues/816

我怎样才能做到这一点?

到目前为止,我已经这样做了,但它不起作用:

class ExcelFile < ActiveRecord::Base
  belongs_to :insertion 
  has_attached_file :excel
  validates_attachment_content_type :excel, content_type: [ "application/vnd.ms-excel",
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "application/msword",
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]


  def after_flush_writes
    super
    byebug
    file = Roo::Excelx.new(self.excel.url(:original, timestamp: false))
    input_from_generals self.id, file
    input_from_financials self.id, file
  end

我尝试使用after_commitafter_create 回调来访问self.excel.url,但它不起作用。

【问题讨论】:

  • after_flush_writes 必须在Paperclip::Attachment class 的上下文中定义,否则不会被调用。但是,我的测试表明,简单的 after_createafter_save 回调可以正常工作 - 您应该能够在这些回调中使用 url
  • 谢谢! @BoraMa 我无法使用 after_create 或 after_save 执行此操作,我认为这是因为回形针通过 after_save 回调写出文件。
  • 我的问题与stackoverflow.com/questions/19960471/…类似,但我不知道他们是如何解决问题的。
  • 您链接的问题不同 - OP 需要对 物理文件 执行某些操作,因此他需要在回调时将其刷新到磁盘。您只需要在我的测试中甚至在将文件物​​理保存到磁盘之前就可以正常工作的 URL。你的情况到底是什么问题?
  • 不,我还需要物理文件。 URL 已正确生成,我能够正确生成,但我收到一条错误消息“找不到文件”,因为我需要物理文件来读取一些数据。

标签: ruby-on-rails ruby ruby-on-rails-4 paperclip


【解决方案1】:

我认为问题可能与回调的顺序有关。

正如上面 cmets 中所讨论的,附件文件确实以after_save callback defined in Paperclip 的形式物理保存到磁盘,该has_attached_file 调用点添加到模型类中。

因此,您必须确保自己的after_save 回调(要处理上传的文件)has_attached_line 之后定义

注意:after_create 回调确实不能使用,因为它在after_save 之前被调用。

【讨论】:

  • 它适用于 after_save 和 URL 中的“公共”前缀。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多