[英]Rails: How to Limit how many files a user can upload in paperclip
I am going to limit the user can upload only one image, if user go to upload more than one it will show error like this 'You can upload max 1 images'我将限制用户只能上传一张图片,如果用户 go 上传多张图片,则会显示如下错误“您最多可以上传 1 张图片”
I am using paperclip gem for upload image it work fine and I add user_id to profile model using migration, Now I am going to limit image upload but getting error我正在使用回形针 gem 上传图像,它工作正常,我使用迁移将 user_id 添加到配置文件 model,现在我要限制图像上传但出现错误
I refer this stackover post Rails:Limiting how many files a user can upload我参考了这篇 stackover 帖子Rails:Limiting How many files a user can upload
models/profile.rb模型/profile.rb
class Profile < ApplicationRecord
belongs_to :user
has_attached_file :profile_image, styles: { medium: "300x300>", thumb: "100x100>" },default_url: "/images/:style/missing.png"
validate :validate_profile_images, :on => :create
private
def validate_profile_images
return if profile_images.count <= 1
errors.add(:profile_images, 'You can upload max 1 images')
end
end
models/user.rb模型/用户.rb
class User < ApplicationRecord
has_many :profiles
end
controllers/profiles_controller.rb控制器/profiles_controller.rb
class ProfilesController < ApplicationController
before_action :find_profile, only: [:show, :edit, :update, :destroy]
def new
@profile = current_user.profiles.build
end
def create
@profile = current_user.profiles.build(profile_params)
if @profile.save
redirect_to profile_path(@profile.user.id)
else
render "new"
end
end
end
private
def profile_params
params.require(:profile).permit(:profile_image,:date_of_birth)
end
def find_profile
@profiles = Profile.where(params[:id])
end
views/profiles/_form.html.erb视图/配置文件/_form.html.erb
<%=simple_form_for @profile, url: profiles_path, html: { multipart: true } do |f| %>
<%= f.label :profile_image,'Your Photo'%></br>
<%= f.file_field :profile_image%></br>
<%=f.label :date_of_birth,'Birth Year'%></br>
<%= f.date_field :date_of_birth,:order => [:day, :month, :year]%></br>
<%= f.submit"Upload Image",:title => "Your photo”%>
<%end%>
We need a little bit more explanation about what do you want to do.我们需要更多关于你想要做什么的解释。
But with what you said and as i understood:但是按照你所说的和我的理解:
You're using a ("has_one_attached") not (has_many_attached)您使用的是 ("has_one_attached") 而不是 (has_many_attached)
And if the file_field is not:multiple, the user shouldn't be able to do upload more than one file.如果 file_field 不是:multiple,则用户不能上传多个文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.