Search code examples
ruby-on-rails-4carrierwavedynamic-data

How to save dynamic number of images using carrierwave


I'm using gem Carrierwave with fog to upload my images to AWS S3.

Right now, I have static memories like this.

class CreateImagePosts < ActiveRecord::Migration
  def change
    create_table :image_posts do |t|
      t.string :img1
      t.string :img2
      t.string :img3
      t.string :img4
      t.string :img5
      t.string :img6
      t.string :img7
      t.string :img8

      t.timestamps null: false
    end
  end
end

But I want to make it possible to upload dynamic numbers of images not like present setting(limited in number of images).

My model looks like this.

class ImagePost < ActiveRecord::Base   

    mount_uploader :img1, S3uploaderUploader
    mount_uploader :img2, S3uploaderUploader
    mount_uploader :img3, S3uploaderUploader
    mount_uploader :img4, S3uploaderUploader
    mount_uploader :img5, S3uploaderUploader
    mount_uploader :img6, S3uploaderUploader
    mount_uploader :img7, S3uploaderUploader
    mount_uploader :img8, S3uploaderUploader

end

Any suggestions or documents that I can read? Thanks.


Solution

  • Create model Attachment with has_many relation:

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

    Migrations:

    class CreateAttachments < ActiveRecord::Migration
      def change
        create_table :attachments do |t|
          t.integer :image_post_id
          t.string :img
        end
        add_index :attachments, :image_post_id
      end
    end
    

    Now you can create any number of images:

    image_post = ImagePost.create
    images.each do |image|
      image_post.attachments.create(img: image)
    end