我正在使用CarrierWave,截至目前,该画廊向公众开放,没有所有权。我想设置一个,用户不必创建一个Gallery。唯一的选择应该是将照片上传到他们的帐户,我希望将每个用户照片上传限制为最多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
照片控制器:
class PhotosController&lt; ApplicationController中
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
答案 0 :(得分:1)
限制用户访问
要限制用户访问某些模型,我会使用类似CanCan的内容。
它会让你做这样的事情:
## ability.rb
# Allow user to CRUD pictures belonging to own gallery
can :manage, Picture, gallery: {user: user}
在控制器中,您可以执行以下操作:
# picture_controller.rb
# assuming a nested route, e.g. galleries/1/pictures
load_and_authorize_resource :gallery
load_and_authorize_resource :picture, through: :gallery
这将确保每个用户只能看到他或她自己的照片。
限制图库中的图片数量
我认为你的验证方法还可以。
我会简化它:
validate :quota
private
def quota
return unless user
if gallery.pictures.count > 4
errors[:base] << "Maximum photos uploaded, delete to upload more"
end
end
错误消息可能应该进入区域设置文件。
自动为每个用户创建图库
要执行此操作,请确保Gallery模型与User具有belong_to
关联。然后在User模型的回调中创建库:
# models/user.rb
after_create :setup_gallery
private
def setup_gallery
Gallery.create(user: self)
end
一般说明
定义has_many
关系时,应使用复数名称,例如has_many :users
或has_many :galleries
。