2010-07-07 13 views
0

특정 레코드에 대한 사용자 정의 이미지 업로드가 있고 모델에 두 개의 열을 추가한다고 가정 해 보겠습니다.ActiveRecord 사용자 정의 필드 방법

thumbnail_url thumbnail_path

지금 내가 가진 폼이 있다고 가정 할 수 있습니다 : 다중 형태로 업로드 된 파일의 파일 필드. 나는 어떻게 든 모델 픽업에 주어진 해쉬 파일을 가져 와서 업로드를 수행하고 모델의 일부분으로 저장하는 커스텀 메소드로 넘겨 줄 필요가있다.

def initialize(options = nil) 
    if options 
    if options[:file] 
     self.upload_thumbnail(options[:file]) 
     options.delete(:file) 
    end 
    super options 
    else 
    super 
    end 
end 

def update_attributes(options = nil) 
    if options 
    if options[:file] 
     self.upload_thumbnail(options[:file]) 
     options.delete(:file) 
    end 
    super options 
    else 
    super 
    end 
end 

그것은 작동하지만, 나는 여기에 몇 가지 불필요한 오버 라이딩을하고있는 중이 야 :

는 지금은이 일을하고 있습니다. 이 작업을 수행하는 간단한 방법이 있습니까? 아마도 단지 하나의 메소드를 오버라이드해야 할 필요가있는 것일까?

답변

2

당신은 virtual attributes을 찾고 있습니다. 그냥 정의 :

def file 
    # Read from file or whatever 
end 

def file=(value) 
    # Upload thumbnail and store file 
end 

initialize, update_attributes와 사촌 당신을위한 방법을 선택합니다.

그 또는 번거 로움을 덜어주고 칸다다가 제안한대로 paperclip을 사용하십시오.

0

paperclip 보석을 사용하여 생각 해 봤어? 그것은 당신이 질문에 설명하는 기능을 수행합니다.

관련 문제