2
votes

I'm using CanCan for defining a users abilities, but I just ran into a snag where I'm trying to only allow the user to manage a model through it's parent.

For example. A book has an author, a book has many chapters. I want only the author to be able to manage chapters. My book model has an author_id. My chapter model has a book_id.

in my Ability.rb file I have

 user.has_role? :author
            can :manage, Book, :author_id => user.id
            can :manage, Chapter
            can :read, :all
        else

but I don't see anywhere in the documentation where I define that the author can only manage the chapters of the book. Is there another way to authorize a book and all it's relationships? Or am I supposed to somehow define the chapter as belonging to the book? I am not saving the chapter through the book model (it is not nested).

1

1 Answers

1
votes

A possible approach:

 user.has_role? :author
            can :manage, Book, :author_id => user.id
            can :manage, Chapter do |chapter|
              chapter.book.author_id == user.id
            end
            can :read, :all
        else

Maybe there's a better solution...