A
A
Andrey2016-11-23 13:53:41
ruby
Andrey, 2016-11-23 13:53:41

(Sinatra) How to load multiple images in CarrierWave?

I tried to create another model (Attachment), but it didn't work.
I think the controller needs something like this

post '/posts' do
  @post = Post.new(
    :image        => params[:image],
  )
  @post.image = params[:image]
  #binding.pry
  if @post.save!
    redirect :"/"
  else
    redirect :"/new"
  end
end

or in the form iterate in name=""
My view
<form action="/posts" method="post" role="form" enctype="multipart/form-data">
    <input type='file' name='image' class='form-control'>
    <input type='file' name='image' class='form-control'>
    <input type='file' name='image' class='form-control'>
    <button type="submit" class="btn btn-success">Submit</button>
</form>

My migration
class CreatePosts < ActiveRecord::Migration[5.0]
  def change
    create_table :posts do |t|
      t.string :image

      t.timestamps null: false 
    end
  end
end

My Model
class Post < ActiveRecord::Base
  mount_uploader :image, ImagesUploader
end

My action
post '/posts' do
  @post = Post.new(params[:post])
  @post.image = params[:image]
  #binding.pry
  if @post.save!
    redirect :"/"
  else
    redirect :"/new"
  end
end

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Grudinkin, 2016-11-24
@andreychumak

It may be possible to do without an additional table, but the solution will be too complicated. Therefore, you need to make a post_attachments table, link it with posts in the migration, and of course you need the image field, you should get something like:

Сlass CreatePostAttachment < ActiveRecord::Migration
  def change
    create_table :post_attachments do |t|
      t.references :post, index: true
      t.string :image
      t.timestamps null: false
    end
    add_foreign_key :post_attachments, :posts
  end
end

Since you are using pure html, the view should look something like this, I might be wrong, I'm used to haml:
<label for="post_image">Выберите одну  или несколько фотографий</label>
<div class="field">
<input multiple="multiple" name="post_attachments[image][]" type="file" id="post_attachments_image">
</div>

Controller:
if @post.save
  unless params[:post_attachments].blank?
          params[:post_attachments]['image'].each do |a|
            @post.post_attachments.create!(:image => a)
          end
  redirect :"/"
  ....

@post.image = params[:image]and the corresponding field, respectively, must be removed from the posts.
In models:
class PostAttachment < ActiveRecord::Base
  mount_uploader :image, ImagesUploader
  belongs_to :post
end

class Post < ActiveRecord::Base
  has_many :post_attachments, :dependent => :destroy
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question