W
W
weare1382015-01-21 18:06:51
Ruby on Rails
weare138, 2015-01-21 18:06:51

How to multi-upload images with Carrierwave?

Hello! Actually the question is in the title of the topic, I use carrierwave. There is an image_uploader class

class ImageUploader < CarrierWave::Uploader::Base

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

end

And there is a photo.rb model to which the loader is mounted
class Photo < ActiveRecord::Base
  mount_uploader :image, ImageUploader
  belongs_to :photoable, polymorphic: true
  belongs_to :post
end

there is also a post.rb model that is linked by a polymorphic association to the photo.rb model
class Post < ActiveRecord::Base
  has_many :comments
  has_many :post_attachments
  validates :title, :body, presence: true
  has_many :photos, as: :photoable
  accepts_nested_attributes_for :photos
end

and there is parsial with form for this model (post) _form.html.haml
= form_for [:admin, @post], html: { multipart: true } do |f|
  = f.fields_for :photos do |photo_fields|
    = photo_fields.file_field :image, multiple: true
  = f.text_field :title, class: "form-control", placeholder: "Заголовок"
  = f.text_area :body, rows: 12, class: "form-control", placeholder: "Сообщение"
  .pull-right
    = f.submit "Отправить", class: "btn btn-success"

and the whole thing works only for one image, when I try to upload several images, the server log swears at Unpermitted parameters: image
how to fix it?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
Eugene Burmakin, 2015-01-22
@weare138

https://github.com/savanr/rails-carrierwave-multip... working example

V
vsuhachev, 2015-01-22
@vsuhachev

The problem is that you do not create many Photo objects each with one picture (as you described in your model), but create one Photo and try to stick several image files into
it
. one field with pictures, don't forget to allow it for strong parameters

= form_for [:admin, @post], html: { multipart: true } do |f|
    = f.file_field :images, multiple: true

2) In the controller method, iterate over the params[:images] array and for each image create its own Photo object and bind it to the parent Post
params[:images].each do |image|
  @post.photos.build(image: image)
end

S
Sergey Krasnodemsky, 2015-01-21
@Prognosticator

stackoverflow.com/questions/23137495/ruby-on-rails...

V
Viktor Vsk, 2015-01-21
@viktorvsk

patshaughnessy.net/2014/6/16/a-rule-of-thumb-for-s...
I wouldn't say what exactly is on topic, but read it. Even if you don't understand, save for the future

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question