4

EDITED: я добавил решение в конце.ActiveAdmin с CarrierWave и несколькими файловыми файлами

Я точно следовал за alestuber's instructions, многопрофильный трюк помог мне успешно работать с загрузкой нескольких изображений. Но я все еще ошибаюсь на выставке изображений.

Я использую Rails 4.2.1, ActiveAdmin 1.0.0.pre1 и MySql.

Мой код:

# Gemfile 
# (...) 
gem 'carrierwave', github: 'carrierwaveuploader/carrierwave' 
gem "mini_magick" 
# (...) 

# migration 
class CreateProducts < ActiveRecord::Migration 
    def up 
    create_table :products do |t| 
     t.string :name 
     t.string :slug, null: false 
     t.decimal :price, precision: 8, scale: 2 
     t.text :description 
     t.text :images, array: true 
     t.references :category 

     t.timestamps null: false 
    end 
    add_index :products, :slug, unique: true 

    Product.create_translation_table! :name => :string, :description => :text 
    end 

    def down 
    drop_table :products 
    Product.drop_translation_table! 
    end 
end 

#app/uploaders/image_uploader.rb 
class ImageUploader < CarrierWave::Uploader::Base 

    include CarrierWave::MiniMagick 
    storage :file 

    def store_dir 
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" 
    end 

    version :thumb do 
    process :resize_to_fit => [200, 200] 
    end 

    def extension_white_list 
    %w(jpg jpeg gif png) 
    end 
end 

#app/models/product.rb 
class Product < ActiveRecord::Base 
    belongs_to :category 

    translates :name, :description 
    active_admin_translates :name, :description 

    extend FriendlyId 
    friendly_id :name, use: :slugged 

    mount_uploaders :images, ImageUploader 

    def to_s 
    name 
    end 
end 

#app/admin/product.rb 
ActiveAdmin.register Product do 
    permit_params :category_id, :price, translations_attributes: [:id, :locale, :name, :description, :_destroy], images: [] 

    index do 
    selectable_column 
    column :name 
    column :category 
    column :price do |product| 
     number_to_currency product.price 
    end 
    translation_status_flags 
    actions 
    end 

    show do 
    attributes_table do 
     row :slug 
     translated_row :name 
     translated_row :description 
     row :category 
     row :price do |product| 
     number_to_currency product.price 
     end 
     row :images do 
     ul do 
      product.images.each do |image| 
      li do 
       image_tag(image.url(:thumb)) 
      end 
      end 
     end 
     end 
    end 

    active_admin_comments 
    end 

    form html: { multipart: true } do |f| 
    f.semantic_errors 

    f.inputs do 
     f.translated_inputs auto_sort: false do |t| 
     t.input :name 
     t.input :description 
     end 
    end 

    f.inputs do 
     f.input :category 
     f.input :price 
     f.input :images, as: :file, input_html: { multiple: true } 
    end 

    actions 
    end 
end 

Ошибка:

Started GET "/uploads/product/images/1/thumb_%5B%22image_1.jpg%22%2C%20%22image_2.png%22%5D" for 10.0.2.2 at 2015-07-14 13:01:43 +0000 

ActionController::RoutingError (No route matches [GET] "/uploads/product/images/1/thumb_%5B%22image_1.jpg%22%2C%20%22image_2.png%22%5D") 

Кажется, объект сохраняется в базе данных является массив из одного элемента, независимо от количества файлов у меня есть выбор в загрузке форма. Изображения сохраняются как ожидалось в файловой системе.

Отредактировано:

Product.find(...).images.inspect возвращается:

"[#<ImageUploader:0xd4afc24 @model=#<Product id: 1, name: \"Camiseta\", slug: \"camiseta\", price: #<BigDecimal:d4ac010,'0.599E2',18(18)>, description: \"\", images: \"[\\\"image_1.jpg\\\", \\\"image_2.png\\\"]\", category_id: 1, created_at: \"2015-07-14 13:01:27\", updated_at: \"2015-07-14 16:41:36\">, @mounted_as=:images, @storage=#<CarrierWave::Storage::File:0xd4afbe8 @uploader=#<ImageUploader:0xd4afc24 ...>>, @file=#<CarrierWave::SanitizedFile:0xd4af904 @file=\"/vagrant/public/uploads/product/images/1/[\\\"image_1.jpg\\\", \\\"image_2.png\\\"]\", @original_filename=nil, @content_type=nil>, @versions={:thumb=>#<ImageUploader::Uploader94172950:0xd4af8dc @model=#<Product id: 1, name: \"Camiseta\", slug: \"camiseta\", price: #<BigDecimal:d4ac010,'0.599E2',18(18)>, description: \"\", images: \"[\\\"image_1.jpg\\\", \\\"image_2.png\\\"]\", category_id: 1, created_at: \"2015-07-14 13:01:27\", updated_at: \"2015-07-14 16:41:36\">, @mounted_as=:images, @parent_version=#<ImageUploader:0xd4afc24 ...>, @storage=#<CarrierWave::Storage::File:0xd4af8a0 @uploader=#<ImageUploader::Uploader94172950:0xd4af8dc ...>>, @file=#<CarrierWave::SanitizedFile:0xd4af580 @file=\"/vagrant/public/uploads/product/images/1/thumb_[\\\"image_1.jpg\\\", \\\"image_2.png\\\"]\", @original_filename=nil, @content_type=nil>, @versions={}>}>]" 

Product.find(...).images.first.url возвращается:

"/uploads/product/images/1/%5B%22image_1.jpg%22%2C%20%22image_2.png%22%5D" 

Любая идея, где проблема ??

Заранее благодарен!

EDITED: решение состоит в том, чтобы добавить сериализацию: изображения к модели продуктов. Так просто! Благодаря @johnmcl от CarrierWave github.

+0

Что возвращает 'Product.find (...). Images.inspect'? –

+0

@TimoSchilling, я добавил ответ на ваш вопрос. –

+0

@GlauberSantana вы можете опубликовать свой последний код в виде? – DogEatDog

ответ

1

Похоже, что вы неправильно вызываете версию изображения (в этом случае большой палец). Попробуйте это ...

show do 
attributes_table do 
    row :slug 
    translated_row :name 
    translated_row :description 
    row :category 
    row :price do |product| 
    number_to_currency product.price 
    end 
    row :images do 
    ul do 
     product.images.each do |image| 
     li do 
      image_tag(image.thumb.url) 
     end 
     end 
    end 
    end 
end 
+0

MilesUA, я считаю, что проблема в том, что несущая волна сохраняет объект в базе данных (например, ["image_1.jpg", "image_2.jpg"]). Патч не работает. –

2

Я думал, что загрузка нескольких файлов все еще находится в стадии бета-тестирования.

Когда я хочу иметь несколько изображений для одной модели, я просто создаю модель ModelImage и сделаю one-to-many отношений между ними.

+0

QQQ, я думаю то же самое. –

Смежные вопросы