Rails 4 carrierwave gem TypeError分配给上传者

时间:2015-01-21 10:08:19

标签: ruby-on-rails ruby-on-rails-4 carrierwave

我使用carrierwave gem在嵌套表单上设置图片上传。上传者看起来像:

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 %>

create中的CarsController操作如下:

@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#create can't cast Array tocar_images字段已作为cars字段添加到json表中。根据carrierwave github上的说明这是正确的,但它在表单提交上抛出了上述错误。导致此错误的原因是什么?如何更正代码以便表单提交?

2 个答案:

答案 0 :(得分:2)

我有同样的错误。

  

TypeError:无法将数组转换为

如文档https://github.com/carrierwaveuploader/carrierwave#multiple-file-uploads所述,您需要进行迁移

rails g migration add_avatars_to_users avatars:json

问题出在类型列 json 中。 SQLite3和MySQL在PostgreSQL中没有这种类型。您可以将其迁移为 text

rails g migration add_avatars_to_users avatars:text

对我来说,这是他的工作。

答案 1 :(得分:1)

与sqlite3相同的错误:

将它放在你的模型中:

serialize :avatars, Array