这是我的第一个问题stackoverflow。
我尝试一次修改上传多个文件。
new.html.erb
<%= form_for(@attractions) do |f| %>
<div class="form-group">
<%= f.label :name, t("attraction.name"), class: "col-md-2 control-label" %>
<div class="col-md-10">
<%= f.text_field :name, class: "form-control" %>
</div>
</div>
<div class="form-group">
<%= f.fields_for :attraction_photos do |att_photo| %>
<%= att_photo.label :photo, t("attraction.attraction_photo"), class: "col-md-2 control-label" %>
<div class="col-md-10">
<%= att_photo.file_field :photo, class: "form-control", multiple: true %> // <==== I add this
</div>
<% end %>
</div>
attraction_controller
def new
@attractions = Attraction.new
@attractions.attraction_photos.build
end
def create
@attractions = current_user.attractions.build(attraction_params)
if @attractions.save
flash[:success] = "success"
redirect_to attractions_path
else
flash[:danger] = @attractions.errors.full_messages
render action: :new
end
end
def attraction_params
params.require(:attraction).permit(:name, :longitude, :latitude, :address, :phone, :category_id, attraction_photos_attributes: [:photo => []])
end
我得到了参数
{
"name" => "name",
"longitude" => "111",
"latitude" => "222",
"address" => "addresss",
"phone" => "phone",
"category_id" => "1",
"attraction_photos_attributes" => {
"0" => {
"photo" => [#, @original_filename = "aaaaaaaaaaaa.png", @content_type = "image/png", @headers = "Content-Disposition: form-data; name=\"attraction[attraction_photos_attributes][0][photo][]\"; filename=\"aaaaaaaaaaaa.png\"\r\nContent-Type: image/png\r\n" > , #, @original_filename = "bbbbbbbbbbb.png", @content_type = "image/png", @headers = "Content-Disposition: form-data; name=\"attraction[attraction_photos_attributes][0][photo][]\"; filename=\"bbbbbbbbbbb.png\"\r\nContent-Type: image/png\r\n" > ]
}
}
}
我想我应该使用循环来创建照片。但数据结构并不是我想要的。谢谢你的帮助。
Eidt
吸引力模型
class Attraction < ActiveRecord::Base
belongs_to :user
belongs_to :category
has_many :attraction_photos, dependent: :destroy
accepts_nested_attributes_for :attraction_photos
...
end
吸引力照片模型
class AttractionPhoto < ActiveRecord::Base
belongs_to :attraction
mount_uploader :photo, AttractionImageUploader
end
答案 0 :(得分:0)
你有两个选择
第一个选项使用数据库中的json
字段上传图片。并非所有db都允许这样做,例如某些mysql2
db不允许您在数据库中使用json
类型字段。使用这个也不是轨道上的红宝石最佳实践
rails carrierwave, one user has many image
另一个选项来自此解决方案,您不会在数据库中使用JSON字段,而是创建一个单独的表
Rails 4 multiple image or file upload using carrierwave
现在请告诉我为什么你不想使用这个解决方案,因为我实施了两个,我会尽力帮助你
同样根据您的问题,目前尚不清楚您遇到的问题