ruby-on-rails - 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%>
解决方案
我们需要更多关于你想要做什么的解释。
但是按照你所说的和我的理解:
您使用的是 ("has_one_attached") 而不是 (has_many_attached)
- “has_one”应该将关系限制为只有 1 条记录。
如果 file_field 不是 :multiple,则用户不能上传多个文件。
推荐阅读
- javascript - 如何从用户 twitter api + javascript 检索所有推文
- python - Discord Self-Bot:加入服务器/公会时直接向用户发送消息
- javascript - Emscripten:使用 pthread 时的自定义消息处理程序
- biztalk - Can BizTalk be used to fetch data from a dynamic URL?
- html - 如何将容器和标签与 Bootstrap 中的复选框对齐?
- docker-compose - 如何从另一个 docker 容器运行 mecab
- azure - 如何使用 Azure Databricks 访问 Azure Cosmos DB 分析存储?
- c# - 可以调用 WPF 类型编辑器的构造函数(从 ITypeEditor 继承)?
- php - 获取库存数量的 SQL SELECT 查询不在函数中返回值(但来自 phpMyAdmin)
- postgresql - 返回整数和布尔值的二维数组