首页 > 解决方案 > Rails:如何限制用户可以在回形针中上传的文件数量

问题描述

我将限制用户只能上传一张图片,如果用户上传多张图片,则会显示如下错误“您最多可以上传 1 张图片”

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

我参考了这篇 stackover 帖子 Rails:Limiting How many files a user can upload

模型/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

模型/用户.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%>

标签: ruby-on-railsrubyruby-on-rails-5

解决方案


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

但是按照你所说的和我的理解:

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

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

如果 file_field 不是 :multiple,则用户不能上传多个文件。


推荐阅读