拥有模型用户,项目,文档,问题,评论,能力:
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
项目的能力正常,但创建文档失败。 问题:
答案 0 :(得分:0)
用于创建文档
在才能类中添加“can:create,Document”,因为当时创建操作被称为“项目”,该文档为nil。
评论的写作能力:
你能解释一下你想要达到的目标吗?如果您希望用户阅读其他用户评论,那么
在用户模型中添加几个关系:
has_many:documents,:through =&gt; :项目
has_many:comments,:through =&gt; :文档
然后在你的能力类中添加
可以:阅读,评论,:commentable_id =&gt; user.comment_ids
答案 1 :(得分:0)
InheritedResources需要添加belongs_to param:
belongs_to :project, :optional => true
了解更多@ https://github.com/ryanb/cancan/wiki/Inherited-Resources