0

拥有模型用户、项目、文档、问题、评论、能力:

class User < ActiveRecord::Base
  has_and_belongs_to_many :projects
end

class Project < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_many :documents
end

class Issues < ActiveRecord::Base
  belongs_to :project
  has_many :comments, :as => :commentable
end

class Document < ActiveRecord::Base
  belongs_to :project
  has_many :comments, :as => :commentable
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.current

    can :read, Project, :id => user.project_ids
    can :manage, Document, :project => { :id => user.project_ids }
  end
end

路线:

resources :projects, :shallow => true, :path => '/', :only => :show do
  resources :documents do
    resources :comments
  end
  resources :issues do
    resources :comments
  end
end

控制器:

class DocumentsController < InheritedResources::Base
  load_and_authorize_resource :project
  load_and_authorize_resource :document, :through => :project, :shallow => true

  # GET /1/documents
  # GET /1/documents.json
  def index
    @project = Project.find(params[:project_id])
    @documents = @project.documents.page(params[:page])

    respond_to do |format|
      format.html
      format.json { render :json => @documents }
    end
  end

  # POST /1/documents/new
  # POST /1/documents/new.json
  def new
    @project = Project.find(params[:project_id])
    @document = @project.documents.build

    respond_to do |format|
      format.html
      format.json { render :json => @document }
    end
  end

  # POST /1/documents
  # POST /1/documents.json
  def create
    @project = Project.find(params[:project_id])
    @document = @project.documents.build(params[:document])

    respond_to do |format|
      if @document.save
        format.html { redirect_to @document, notice: 'Document was successfully created.' }
        format.json { render json: @document, status: :created, location: @document }
      else
        format.html { render action: "new" }
        format.json { render json: @document.errors, status: :unprocessable_entity }
      end
    end
  end
end

项目能力还可以,但是创建文档失败。问题:

  1. 我对文档能力做错了什么?
  2. 如何编写注释功能(多态和嵌套)?
4

2 回答 2

0

InheritedResources 需要添加belongs_to 参数:

belongs_to :project, :optional => true

查找更多 @ https://github.com/ryanb/cancan/wiki/Inherited-Resources

于 2013-04-24T09:38:12.130 回答
0

用于创建文档

在能力类中添加“can :create, Document”,因为当时创建操作被称为“项目”对于该文档是 nil。

评论写作能力:

你能解释一下你想要达到的目标吗?如果您想让用户阅读其他用户的评论,那么

在用户模型中添加一些关系:

has_many :documents, :through => :projects

has_many :comments, :through => :documents

然后在你的能力类中添加

可以:阅读,评论,:commentable_id => user.comment_ids

于 2013-04-24T08:58:38.843 回答