Answer the question
In order to leave comments, you need to log in
(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
<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>
class CreatePosts < ActiveRecord::Migration[5.0]
def change
create_table :posts do |t|
t.string :image
t.timestamps null: false
end
end
end
class Post < ActiveRecord::Base
mount_uploader :image, ImagesUploader
end
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
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
<label for="post_image">Выберите одну или несколько фотографий</label>
<div class="field">
<input multiple="multiple" name="post_attachments[image][]" type="file" id="post_attachments_image">
</div>
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. 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 questionAsk a Question
731 491 924 answers to any question