本文介绍了如何使用载波保存动态图像数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将宝石 Carrierwave
与 fog
一起使用将我的图像上传到 AWS S3
。
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).
我的模型如下。
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.
推荐答案
使用创建模型
关系:附件
has_many
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
迁移:
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
这篇关于如何使用载波保存动态图像数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!