我正在使用 CarrierWave,到目前为止,该画廊对公众开放,没有所有权。我想设置一个,用户不必创建画廊。唯一的选择应该是将照片上传到他们的帐户,我想将每张用户照片上传限制为最多 5 张。因此,如果用户 16 登录,他们可以选择将最多 5 张照片上传到他们的个人资料。一旦达到该限制,如果用户尝试上传更多,它应该说“最大上传照片,删除以上传更多”。我不确定如何解决这个问题。
photo.rb 模型:
class Photo < ActiveRecord::Base
attr_accessible :title, :body, :gallery_id, :name, :image, :remote_image_url
has_many :user, :through => :gallery
has_many :gallery
mount_uploader :image, ImageUploader
LIMIT = 5
validate do |record|
record.validate_photo_quota
end
def validate_photo_quota
return unless self.user
if self.gallery.user(:reload).count >= LIMIT
errors.add(:base, :exceeded_quota)
end
end
end
照片控制器:
类照片控制器 < 应用控制器
def new
@photo = Photo.new(:gallery_id => params[:gallery_id])
end
def create
@photo = Photo.new(params[:photo])
if @photo.save
flash[:notice] = "Successfully created photos."
redirect_to @photo.gallery
else
render :action => 'new'
end
end
def edit
@photo = Photo.find(params[:id])
end
def update
@photo = Photo.find(params[:id])
if @photo.update_attributes(paramas[:photo])
flash[:notice] = "Successfully updated photo."
redirect_to @photo.gallery
else
render :action => 'edit'
end
end
def destroy
@photo = Photo.find(params[:id])
@photo.destroy
flash[:notice] = "Successfully destroyed photo."
redirect_to @photo.gallery
end
end
画廊控制器:
class GalleriesController < ApplicationController
def index
@galleries = Gallery.all
end
def show
@gallery = Gallery.find(params[:id])
end
def new
@gallery = Gallery.new
end
def create
@gallery = Gallery.new(params[:gallery])
if @gallery.save
flash[:notice] = "Successfully created gallery."
redirect_to @gallery
else
render :action => 'new'
end
end
def edit
@gallery = Gallery.find(params[:id])
end
def update
@gallery = Gallery.find(params[:id])
if @gallery.update_attributes(params[:gallery])
flash[:notice] = "Successfully updated gallery."
redirect_to gallery_url
else
render :action => 'edit'
end
end
def destroy
@gallery = Gallery.find(params[:id])
@gallery.destroy
flash[:notice] = "Successfully destroy gallery."
redirect_to galleries_url
end
end