Getting Cancan load_and_authorize_resource working as part of a custom create action

Trying to configure Cancan in my application and have problems with my PostsController .

In a nutshell, when Post is created, I would like it to be associated with current_user , so my create action looks something like this:

 class PostsController < ApplicationController before_filter :login_required, :except => [: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 

I'm not quite sure what to do with load_and_authorize_resource (other than the obvious). But what to do in such a situation? Do I need to override load_and_authorize_resource for the create action? or is there another way (read: better) to download the @user and THEN download by creating @post ?

+4
source share
2 answers

A simpler solution to your problem would be to use a nested resource rather than creating a custom action

Directly from the CanCan Wiki:

Nested-resources

As with 1.4, it is also possible to nest through a method, this is usually the current_user method.

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

Here everything will be loaded through the association current_user.projects.

It should also be safer, as the message will be downloaded through the union for other actions in your controller.

+3
source

I think the best solution, since this is a unique problem, you can change the line load_and_authorize_resource to this:

 load_and_authorize_resource :except => [:create] 

And the action for this:

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

All Articles