2015-01-21 53 views
2

我使用carrierwave gem在嵌套窗體上設置圖片上傳。上傳者的樣子:Rails 4 carrierwave gem TypeError分配給上傳者

class CarImageUploader < CarrierWave::Uploader::Base 

    include CarrierWave::MiniMagick 

    if Rails.env.production? 
     storage :fog 
    else 
     storage :file 
    end 

    def store_dir 
     "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" 
    end 

    def default_url 
     'default-no-car-pic.png' 
    end 

    version :thumb do 
     process :resize_to_fit => [50, 50] 
    end 

    def extension_white_list 
     %w(jpg jpeg gif png) 
    end 

end 

這個模型看起來像:

class Car < ActiveRecord::Base 

    belongs_to :user 
    has_one :car_info, dependent: :destroy 
    has_one :car_spec, dependent: :destroy 
    accepts_nested_attributes_for :car_spec, :car_info 

    mount_uploaders :car_images, CarImageUploader 

    validates_associated :car_info, :car_spec, presence: true 

end 

視圖形式:

<%= form_for @car, html: { multipart: true, class: "form-horizontal" } do |f| %> 

    <%= f.fields_for :car_spec do |car_spec_field| %> 

     # Fields for car_spec 

    <% end %> 

    <%= f.fields_for :car_info do |car_info_field| %> 

     # Fields for car_info 

    <% end %> 

    <%= f.label :images %> 
    <%= f.file_field :images, multiple: true %> 

    <%= f.submit "Add car" %> 

<% end %> 

CarsControllercreate動作看起來像:

@car = current_user.cars.build(car_params) 
@car.car_images = params[:car][:images] 

respond_to do |format| 
    if @car.save 

    format.html { redirect_to @car, notice: 'Car was successfully created.' } 
    format.json { render :show, status: :created, location: @car } 
    else 
    format.html { render :new } 
    format.json { render json: @car.errors, status: :unprocessable_entity } 
    end 
end 

當我提交表單時,此代碼導致TypeError in CarsController#createcan't cast Array tocar_images字段作爲json字段被添加到cars表中。根據carrierwave github上的說明,這是正確的,但它在表單提交上拋出上述錯誤。什麼是導致這個錯誤,我怎樣才能糾正代碼,以便表單將提交?

+0

你有沒有發現問題? – 2015-09-10 02:49:59

回答

2

我有同樣的錯誤。

TypeError: can't cast Array to

如文檔https://github.com/carrierwaveuploader/carrierwave#multiple-file-uploads說,你需要做的遷移

rails g migration add_avatars_to_users avatars:json 

的問題是在類型列JSON。 SQLite3和MySQL在PostgreSQL中沒有這種類型。你可以把它作爲遷移文本

rails g migration add_avatars_to_users avatars:text 

對我來說工作。

1

同樣的錯誤與sqlite3的:

在你的模型將這個:

serialize :avatars, Array 
相關問題