拥有模型用户、项目、文档、问题、评论、能力:
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
项目能力还可以,但是创建文档失败。问题:
- 我对文档能力做错了什么?
- 如何编写注释功能(多态和嵌套)?