Changnam Hong
Changnam Hong

Reputation: 1679

carrierwave multiple image upload with one button

My question starts from here. I'm using Sqlite3 and my model relation looks like this.

class ImagePost < ActiveRecord::Base
    has_many :attachments
end

My attachment

class Attachment < ActiveRecord::Base
    belongs_to :image_post
    mount_uploader :img, S3uploaderUploader
end

The thing is I want to make my users uploading their images with one button. Right now, I did

<%= form_tag img_upload_create_path, method: "POST", html: { multipart: true } do %>
        <%= hidden_field_tag("image_post_id", @image_post.id ) %>
        <%= hidden_field_tag("user_id", current_user.id ) %>

        <%= file_field_tag 'user_pic', multiple: true, accept: 'image/png,image/gif,image/jpeg' %>

        <%= submit_tag "image-upload", :class => "btn btn-primary btn-lg" %>
      <% end %>

My image_upload controller,

class ImgUploadController < ApplicationController
  def create
    @user_img = Attachment.create(
        hasuk_house_id: params[:image_post_id],
        user_id: current_user.id,
        img: params[:user_pic]
        )
  end
end

But when I submit files, @user_img.img = nil What am I going to do?

Upvotes: 0

Views: 541

Answers (1)

Amr Noman
Amr Noman

Reputation: 2637

After taking a closer look, you have multiple problems going on here, first:

<%= form_tag img_upload_create_path, method: "POST", html: { multipart: true }

should be:

<%= form_tag(img_upload_create_path, { multipart: true, method: "POST"})

( form_tag arguments are structured a bit different from form_for)

and then you need to instruct rails to put your files in params as an array, you do that by using a name convention for form elements. so instead of:

 <%= file_field_tag 'user_pic', multiple: true, accept: 'image/png,image/gif,image/jpeg' %>

you need:

<%= file_field_tag 'user_pic[]', multiple: true, accept: 'image/png,image/gif,image/jpeg' %>

and finally in your controller, you'll have the files in params[:user_pic] which is an array, so you'll have to loop through it and create your attachments for each one:

params[:user_pic].each do |pic|
  Attachment.create(
        hasuk_house_id: params[:image_post_id],
        user_id: current_user.id,
        img: pic
  )
end

Hope that helps.

Upvotes: 1

Related Questions