Created
August 25, 2011 16:21
-
-
Save goncalossilva/1171066 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Ability | |
| include CanCan::Ability | |
| def initialize(user) | |
| can :create, Comment, :post => { :published => true } | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class CommentsController < ApplicationController | |
| load_and_authorize_resource | |
| def create | |
| @comment.save | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <%= form_for @post.comments.new do |f| %> | |
| ... | |
| <% end %> |
Author
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 => :postThen it will build the comment through the post.
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
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?