2016-10-26 11 views
0

컨텐츠 유형에 따라 동적 인 Paperclip gem을 사용하여 단일 테이블 상속을 사용할 계획입니다.내용 유형에 따라 Paperclip의 동적 옵션

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] 

내 질문은 의미가 있기를 바랍니다. 감사.

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를 사용

+0

STI 모델을 사용하는 경우, 서브 클래스 동작으로 수퍼 클래스를 인스턴스화하는 이유는 무엇입니까? 당신은 그것을 수퍼 클래스로서의 File과 Document, Photo, Pdf라고 생각할 것입니다. –

+0

'= simple_form_for Document.new'을 사용하여 양식을 작성했습니다. 나는 File (나는 그냥 Document라고 부름)을 Photo와 Pdf가있는 수퍼 클래스로 생각하고있다. params [: document]를 기반으로 해당 하위 클래스를 인스턴스화해야한다고 제안 하시겠습니까? –

답변

1

당신은 그것을 좋아 할 수 있습니다.

+0

감사합니다. 아름답게 작동합니다! :) –