我使用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
现在应该创建多个图像
当我正在尝试创建时发现此错误
答案 0 :(得分:1)
在模型Article
中安装avatars
而不是avatar
并将您的专栏avatar
更改为:
def change
remove_column :articles, :avatar
add_column :articles, :avatars, :string, array: true, default: []
end