Rails - 使用ckeditor Gem w / CanCan&amp ;;限制浏览用户附件回形针

时间:2014-07-29 02:42:24

标签: ruby-on-rails ckeditor paperclip cancan

我让一切正常,但现在我想限制一些用户能力来执行一些附件操作。

具体而言,能够将所有上传的附件的查看限制为用户实际上传的附件。

以下是我尝试过的 ability.rb 的适用代码段

if user.id
  can :access, :ckeditor
  can [:read, :create, :destroy], Ckeditor::Picture, assetable_id: user.id
  can [:read, :create, :destroy], Ckeditor::AttachmentFile, assetable_id: user.id
end

当我使用CKeditor UI时,出现这种情况,单击图像按钮,然后单击浏览服务器按钮以查看以前上传的图像 - 现在图像浏览器显示所有用户的上传内容。我希望查看的图像仅限于 current_user 的图像。

由于Ckeditor表保存了附件的 assetable_id (即user.id),并且上面的逻辑不能单独工作,我猜测还需要一些自定义控制器逻辑这里。

感谢。

1 个答案:

答案 0 :(得分:3)

我能够使用自定义Ckeditor控制器来解决这个问题。从这里得到一些指导: https://github.com/galetahub/ckeditor/issues/246

首先,我需要复制Ckeditor控制器pictures_controller.rb& attachment_files_controller.rb并将它们放在这里: /app/controllers/ckeditor/

然后,有必要对他们更新index的建议进行一些更新,特别是picture_model.find_all需要在 pictures_controller.rb picture_adapter.find_all(同样attachment_file_adapter.find_all 1}}在 attachment_files_controller.rb

这一切的关键是设置适当的范围:ckeditor_pictures_scope(assetable_id: ckeditor_current_user)& ckeditor_attachment_files_scope(assetable_id: ckeditor_current_user)

一旦这些修订到位,图片和文件浏览器就会出现。附件仅显示该用户的相应文件。

以下是修订后的文件......这些更改都在第4行。

/app/controllers/ckeditor/pictures_controller.rb

class Ckeditor::PicturesController < Ckeditor::ApplicationController

  def index
    @pictures = Ckeditor.picture_adapter.find_all(ckeditor_pictures_scope(assetable_id: ckeditor_current_user))
    @pictures = Ckeditor::Paginatable.new(@pictures).page(params[:page])
    respond_with(@pictures, :layout => @pictures.first_page?)
  end

  def create
    @picture = Ckeditor.picture_model.new
    respond_with_asset(@picture)
  end

  def destroy
    @picture.destroy
    respond_with(@picture, :location => pictures_path)
  end

  protected

  def find_asset
    @picture = Ckeditor.picture_adapter.get!(params[:id])
  end

  def authorize_resource
    model = (@picture || Ckeditor.picture_model)
    @authorization_adapter.try(:authorize, params[:action], model)
  end

end

/app/controllers/ckeditor/attachment_files_controller.rb

class Ckeditor::AttachmentFilesController < Ckeditor::ApplicationController

  def index
    @attachments = Ckeditor.attachment_file_adapter.find_all(ckeditor_attachment_files_scope(assetable_id: ckeditor_current_user))
    @attachments = Ckeditor::Paginatable.new(@attachments).page(params[:page])
    respond_with(@attachments, :layout => @attachments.first_page?)
  end

  def create
    @attachment = Ckeditor.attachment_file_model.new
    respond_with_asset(@attachment)
  end

  def destroy
    @attachment.destroy
    respond_with(@attachment, :location => attachment_files_path)
  end

  protected

  def find_asset
    @attachment = Ckeditor.attachment_file_adapter.get!(params[:id])
  end

  def authorize_resource
    model = (@attachment || Ckeditor.attachment_file_model)
    @authorization_adapter.try(:authorize, params[:action], model)
  end

end