2012-01-27 66 views
0

我有我的用戶需要先上傳圖像,然後分配給另一個模型的場景,所以我用一個通用的模型,要上傳的文件第一次,如何與分離附件模型單獨使用回形針

模型:

class AttachedImage < ActiveRecord::Base 
    belongs_to :attachable, :polymorphic => true 

    has_attached_file :image 
end 

遷移:

class CreateAttachedImages < ActiveRecord::Migration 
    def change 
    create_table :attached_images do |t| 

     t.string  :image_file_name 
     t.string  :image_content_type 
     t.integer  :image_file_size 
     t.datetime :image_updated_at 
     t.references :attachable, :polymorphic => true 

     t.timestamps 
    end 
    end 
end 

和視圖和控制器是這樣的:

class AttachedImagesController < ApplicationController 
    def create 

    @attched_image = AttachedImage.new(params) 

    respond_to do |format| 
     if @attched_image.save 
     format.js 
     else 
     format.js 
     end 
    end 
    end 
end 

視圖部分:

<div id="upload-image-dialog"> 
    <%= form_tag(@attached_image, :method => "POST", :remote => true, :html => { :multipart => true }) do %> 
     <%= file_field_tag :image %> 
     <%= submit_tag("submit") %> 
    <% end %> 
    <h1 style="display:none">Successfully Uploaded.</h1> 
</div> 

這是相當簡單的,但我每次提交此表時,我會得到通過導軌自動添加UTF8領域的一個例外。我無法理解,這不是一個問題吧?我們每天都會寫@model = Model.new(params),希望有人能幫助我解釋發生了什麼,謝謝!

ActiveRecord::UnknownAttributeError (unknown attribute: utf8): 
    app/controllers/attached_images_controller.rb:5:in `new' 
    app/controllers/attached_images_controller.rb:5:in `create' 

回答

1

問題是在這裏:

@attched_image = AttachedImage.new(params) 

你通過所有PARAMS保存(這就是爲什麼你越來越UTF8錯誤,這裏面PARAMS)。它應該是:

@attched_image = AttachedImage.new(params[:attached_image]) 
+0

非常感謝。我剛剛發現它,而我正在努力刪除我的愚蠢問題......無論如何,非常感謝你。 :) – larryzhao 2012-01-30 16:49:39