Rails carrierwave多文件上传在ArticlesController中创建Encoding :: UndefinedConversionError

时间:2017-12-11 13:56:30

标签: ruby-on-rails carrierwave

我使用rails gem carrierwave测试多个上传图片

下面是我一步一步

  • rails new TestUploadImages
  • rails g Article title:string body:text
  • rails generate uploader Avatar
  • rails g migration add_avatar_to_users avatar:string rake db:migrate

config Article model uploader

class Article < ApplicationRecord
  mount_uploader :avatar, AvatarUploader
end

配置_form.html.erb以创建包含图片的文章

<%= form_for @article, html: {multipart: true} do |f| %>
    <p>
        <%= f.label :title %>
        <%= f.text_field :title %>
    </p>
    <p>
        <%= f.file_field :avatars%>
    </p>
    <p>
        <%= f.label :body %>
        <%= f.text_area :body %>
    </p>

    <p>
        <%= f.submit %>
    </p>
<% end %>

article_controller

class ArticlesController < ApplicationController
  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)
    @article.save
    render "show"
  end

  def show
    @article = Article.find(params[:id])
  end

  private 

  def article_params
    params.require(:article).permit(:title, :body, :avatar)
  end
end

这里可以用文章

创建一个图像 下面是尝试创建多个图像
  • 使用article
  • 更改avatar表格avatars

更改_form.html.erb

<p>
    <%= f.file_field :avatars, multiple: true%>
</p>

因为我用过的测试数据库是sqlite3所以,引用来自cariierwave

class Article < ApplicationRecord
  mount_uploader :avatar, AvatarUploader
  serialize :avatars, JSON
end

更改articles_controller强参数

  def article_params
    params.require(:article).permit(:title, :body, {avatars: []})
  end

现在应该创建多个图像

当我正在尝试创建时发现此错误

enter image description here

和终端消息 enter image description here

1 个答案:

答案 0 :(得分:1)

在模型Article中安装avatars而不是avatar

并将您的专栏avatar更改为:

def change
    remove_column :articles, :avatar
    add_column :articles, :avatars, :string, array: true, default: []
end