2017-02-08 22 views
0

我有兩個使用Paperclip附加文件的模型。這兩個模型幾乎完全相同,但是當我在每個類上調用方法'.attachment_name'時,對於第二個模型,它返回nil。Paperclip attachment_name返回零

我在這裏發帖兩個模型代碼未過時,因爲我不知道什麼信息是重要的。

這是第一種模式:

class DocumentationFile < ActiveRecord::Base 
    belongs_to :documentation 

    has_attached_file :file, styles: { large: '720x720>', medium: '300x300>', thumb: '100x100>' }, 
          default_url: '/images/:style/missing.png' 

    validates_attachment :file, content_type: { content_type: [/\Aimage\/.*\Z/, 'application/pdf'] }, 
         size: { in: 0.megabytes..5.megabytes } 


    validates :file, presence: true 
end 

這裏是第二個:

class JobExtra < ActiveRecord::Base 
    belongs_to :job 

    has_attached_file :file 
    validates_attachment :file, content_type: { content_type: [/\Aimage\/.*\Z/, 'application/pdf'] }, 
         size: { in: 0.megabytes..5.megabytes } 
end 

所以當在軌控制檯我試圖用第二個模型兩種模型獲取附件名稱我得到零:

2.3.3 :003 > DocumentationFile.attachment_name 
=> :file 
2.3.3 :004 > JobExtra.attachment_name 
=> nil 

我不明白爲什麼發生了什麼,我做錯了什麼。我試圖將相同的驗證和選項添加到has_attached_file,但它沒有幫助。

所以我已經用盡了想法,這個問題讓我瘋狂。我會很感激任何幫助!

回答

0

我們可以看到你的控制器嗎?我有同樣的問題,我解決它通過在create方法寫:

def create 
    @job.file = params[:job][:file] 
    @job.save 
end 

這背後的原因是,Rails的實際處理文件/圖像,但一切都在模型內部。事情是這樣的:

參數:

{"job"=>{"file"=>#<ActionDispatch::Http::UploadedFile:0x007f 
f342035948 @tempfile=#<Tempfile:/var/folders/_2/....jpg>, @original_filename="....jpg", filename=\"....jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"send"}