【问题标题】:Dynamic options for Paperclip based on the content type基于内容类型的回形针动态选项
【发布时间】:2016-10-26 21:39:43
【问题描述】:

我计划使用 Paperclip gem 使用单表继承,这将基于内容类型动态。

class Document < ActiveRecord::Base
    has_attached_file :file, photo_options #if content type is an image
    has_attached_file :file, pdf_options #if content type is a pdf file
end

class Photo < Document
    # photo specific code
end

class Pdf < Document
    # pdf specific code
end

是否可以根据内容类型使has_attached_file 成为动态的?一个用例是尝试从文件表单上传创建Document 的新实例时:

@document = Document.new params[:document]

我希望我的问题是有道理的。谢谢。

【问题讨论】:

  • 如果您使用的是 STI 模型,为什么要使用子类行为来实例化超类?你不能把它想象成一个文件作为超类和文档、照片和 PDF 作为子类吗?
  • 我正在使用= simple_form_for Document.new 创建表单。我试图将 File(我只是将其称为 Document)视为一个超类,其中 Photo 和 Pdf 作为子类。您是否建议基于 params[:document],我应该实例化相应的子类?

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


【解决方案1】:

你可以这样做:

class Document < ActiveRecord::Base
end

class Photo < Document
  has_attached_file :file, photo_options #if content type is an image
  # photo specific code
end

class Pdf < Document
  has_attached_file :file, pdf_options #if content type is a pdf file
  # pdf specific code
end

class DocumentsController < ApplicationController
  #Assuming is the new method.
  def new
     @document = params[:document_type].classify.safe_constantize.new
  end
end

并在您的表单中使用@document。

【讨论】:

  • 谢谢。工作精美! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-28
  • 2021-08-18
  • 1970-01-01
相关资源
最近更新 更多