Rails:如何限制用户可以在回形针中上传的文件数量



我将限制用户只能上传一张图像,如果用户上传多张图像,它将显示如下错误"您最多可以上传 1 张图像">

我正在使用回形针 gem 上传图像,它工作正常,我使用迁移将user_id添加到配置文件模型,现在我将限制图像上传但出现错误

我参考这个堆栈帖子 Rails:限制用户可以上传的文件数量

models/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

class User < ApplicationRecord
has_many :profiles
end

控制器/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

视图/配置文件/_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%>

我们需要更多关于你想做什么的解释。

但根据你所说的和我的理解:

您使用的是("has_one_attached"(而不是 (has_many_attached(

  • "has_one"应将关系限制为只有 1 条记录。

如果file_field不是:multiple,则用户应该无法上传多个文件。

最新更新