Skip to content

Instantly share code, notes, and snippets.

@goncalossilva
Created August 25, 2011 16:21
Show Gist options
  • Select an option

  • Save goncalossilva/1171066 to your computer and use it in GitHub Desktop.

Select an option

Save goncalossilva/1171066 to your computer and use it in GitHub Desktop.
class Ability
include CanCan::Ability
def initialize(user)
can :create, Comment, :post => { :published => true }
end
end
class CommentsController < ApplicationController
load_and_authorize_resource
def create
@comment.save
end
end
<%= form_for @post.comments.new do |f| %>
...
<% end %>
@goncalossilva

Copy link
Copy Markdown
Author

I always get CanCan::AccessDenied because @comment is not initialized when authorize!() runs.

Is there a way to check if Post.find(params[:post_id]) is published instead of trying to access the non-existent @comment.post?

@ryanb

ryanb commented Aug 25, 2011

Copy link
Copy Markdown

How are you passing the post_id to the comment? If it's in the params[:comment][:post_id] it should all work. However if you have nested routes and need to build the comment through the post like Post.find(params[:post_id]).comments.build then you'll need to make it nested in CanCan.

load_and_authorize_resource :post
load_and_authorize_resource :comment, :through => :post

Then it will build the comment through the post.

@goncalossilva

Copy link
Copy Markdown
Author

Yes, I have nested routes. Thanks for clarifying!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment