我在模型photos
中上传了多个logos
和多个Cover
。它们都正确保存在数据库中,但不是在cloudinary中。
由于logos
和photos
的配置相同,我只会向您展示一次。
我已跟随this配置多个上传和this进行cloudinary配置。
cover.rb
class Cover < ApplicationRecord
has_many :cover_attachments
accepts_nested_attributes_for :cover_attachments
end
cover_attachment.rb
class CoverAttachment < ApplicationRecord
mount_uploader :photo, PhotoUploader
mount_uploader :logo, LogoUploader
belongs_to :cover
end
photo_uploader.rb
class PhotoUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
include Cloudinary::CarrierWave
process convert: 'png'
process tags: ['cover_photo']
version :standard do
process resize_to_fill: [100, 150, :north]
end
version :thumbnail do
resize_to_fit(50, 50)
end
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
_form.html.slim
= simple_form_for [current_user, @book, @cover], html: { multipart: true } do |f|
= f.label :photo, 'photos'
= f.file_field :photo, multiple: true, name: "cover_attachments[photo][]"
...
schema.rb
create_table "cover_attachments", force: :cascade do |t|
t.string "photo"
t.string "logo"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "cover_id"
end
create_table "cover_type_users", force: :cascade do |t|
t.integer "cover_id"
t.string "cover_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["cover_id"], name: "index_cover_type_users_on_cover_id", using: :btree
end
create_table "covers", force: :cascade do |t|
...
end
covers_controller.rb
def create
if @cover.save
params[:cover_attachments]['photo'].each do |a|
@cover_attachment = @cover.cover_attachments.create!(photo: a)
end
...
end
end
终端输出
Processing by CoversController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"VnBZ7iysnNsl8oVbBjqvPd8ZbsMQrn0JQCOtg5kSHnjovVOhFPBcyu1xzXCytVkXrHH1b+TcpbnCire7XB9hSg==", "cover"=>{"design_tags"=>"kjh", "client_wishes"=>"kj", "format"=>"12X24", "isbn"=>"", "selling_price"=>"", "book_id"=>"210"}, "cover_attachments"=>{"photo"=>[#<ActionDispatch::Http::UploadedFile:0x007f8698ce73b0 @tempfile=#<Tempfile:/var/folders/0w/pznf2h6j0q9gqcbcthg1kgm40000gn/T/RackMultipart20170816-9346-1qrdd6j.jpg>, @original_filename="andrew-neel-266219.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"cover_attachments[photo][]\"; filename=\"andrew-neel-266219.jpg\"\r\nContent-Type: image/jpeg\r\n">]}, "commit"=>"poursuivre", "user_id"=>"112", "book_id"=>"210", "id"=>"188"}
....
SQL (6.8ms) INSERT INTO "cover_attachments" ("photo", "created_at", "updated_at", "cover_id") VALUES ($1, $2, $3, $4) RETURNING "id" [["photo", "j43shp8bkjfg0wsc8y3r.png"], ["created_at", 2017-08-16 10:12:58 UTC], ["updated_at", 2017-08-16 10:12:58 UTC], ["cover_id", 188]]