Rails 3 - CanCan - 定义创建权限

时间:2010-12-03 19:34:26

标签: ruby-on-rails ruby-on-rails-3 cancan

我的控制器中有以下内容

  def upload

    @attachment = Attachment.build(:swf_uploaded_data => params[:attachment][:attachment], :user_id => current_user.id, :project_id => params[:space_id])
....
    end

CanCan我想要的是只允许用户上传到他们所属的project_id。我确认控制器正在获取正确的信息,没有nils

这是我的康康舞:

can :upload, Attachment do |attachment|
  Rails.logger.info 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX- include CanCan::Ability - ATTACHMENT'  
  Rails.logger.info attachment.inspect
  Rails.logger.info attachment.project

  current_user.try(:role, attachment.space)
end

问题在于,是附件。是零,attachment.project是零?您如何使用CanCan解决此问题,以便确保只有项目团队成员可以将附件上传到项目中?

谢谢

2 个答案:

答案 0 :(得分:5)

我认为最好的方法是使用控制器操作的authorize!方法在较低级别执行此操作。

所以......

#AttachmentController

#Will remove it from cancan
load_and_authorize_resource :except => [:upload]

def upload
 @attachment = Attachment.build(:swf_uploaded_data => params[:attachment][:attachment], :user_id => current_user.id, :project_id => params[:space_id])
  #add the authorize logic explicitly here when you have the attachment model populated
  authorize! :upload, @attachment
end

请告诉我这是否适合您。

答案 1 :(得分:0)

例如,如果您只想为当前循环允许创建事件:

您在视图中使用

link.... if can? :create, @loop.events.new

然后在控制器中

skip_authorize_resource only: [:new, :create]

...

def new
   @event.loop_id = @loop.id
   authorize! :create, @event
end

#similar for create action