我有一个有头像的用户模型。回形针用于允许图像上传。但是,我希望用户能够上传尽可能多的图像(无限制(。如何修改我的模型以允许此类行为? 用户模型如下所示:
class Model < ApplicationRecord
has_attached_file :pic, styles: { medium: "420×633!", thumb: "100x100#" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :pic, content_type: /Aimage/.*z/
has_many :reviews, dependent: :destroy
提前感谢!
您可以将用户的photos
(如果您这样称呼它(存储在单独的模型中,并在User
模型中为其添加关联:
命令行
rails g paperclip photo pic
app/models/user.rb
has_many :photos, dependent: :destroy
app/models/photo.rb
belongs_to :user
has_attached_file :pic, styles: { medium: "420×633!", thumb: "100x100#" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :pic, content_type: /Aimage/.*z/
根据给定的规范,您可以生成另一个模型来保存user_images,这样用户可以拥有无限的图像。
user.rb
class User < ApplicationRecord
has_many :user_images, dependent: :destroy
accepts_nested_attributes :user_images
validates_attachment_content_type :pic, content_type: /Aimage/.*z/
has_many :reviews, dependent: :destroy
end
user_image.rb
Class UserImage < ApplicationRecord
belongs_to :user
has_attached_file :user_image, styles: { medium: "420×633!", thumb: "100x100#" }, default_url: "/images/:style/missing.png"
end
在user_model中添加了accepts_nested_attributes,并在user_image中增加了回形针设置,用于上传图像。