让Cancan的load_and_authorize_resource在自定义创建操作中工作

试图在我的应用程序中设置PostsController并且我的PostsController

简而言之,当创建Post时,我希望它与current_user相关联,因此我的create action看起来像这样:

 class PostsController  [:index, :show] load_and_authorize_resource ... def create # @post = Post.new(params[:post]) # <-- covered by load_and_authorize_resource @user = current_user @post = @user.posts.create(params[:post]) respond_to do |format| ... end ... end 

我不确定load_and_authorize_resource打算做什么(除了明显的)。 但是在这种情况下呢? 我是否需要以某种方式覆盖create操作的load_and_authorize_resource ? 还是有另一种(阅读:更好)的方式来加载@user和那么创建@post

解决问题的更简单方法是使用嵌套资源,而不是创建自定义操作

直接取自CanCan Wiki:

嵌套资源

从1.4开始,它也可以通过方法嵌套,这通常是current_user方法。

  class ProjectsController < ApplicationController load_and_authorize_resource :through => :current_user end 

这里所有内容都将通过current_user.projects关联加载。

这也应该更安全,因为post的加载将通过控制器中其他操作的关联来完成

我认为最好的解决方案,因为这是一个独特的问题,您可以将load_and_authorize_resource行更改为:

 load_and_authorize_resource :except => [:create] 

对此的行动:

 def create authorize! :create, Post current_user.posts.create(params[:post]) end