如何使用载波保存动态数量的图像

How to save dynamic number of images using carrierwave

我正在使用 gem Carrierwavefog 将我的图片上传到 AWS S3

现在,我有这样的静态记忆。

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

但我想上传动态数量的图片成为可能,而不是像现在的设置(限制图片数量)。

我的模型是这样的。

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

有什么建议或我可以阅读的文件吗?谢谢。

使用 has_many 关系创建模型 Attachment

class ImagePost < ActiveRecord::Base
  has_many :attachments
end

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

迁移:

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

现在您可以创建任意数量的图像:

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