Cancan and using has_many relationships for :create

728 views Asked by At

A Book has_many Chapters. A User has_many Books.

I'm using devise and cancancan, and I want to allow a user to :create a chapter for any Book they own. My problem is, a Chapter does not belong to a Book until it exists so in ability.rb -

can [:read, :update, :destroy], Chapter do |chapter|
  chapter.book.user_id == user.id
end

is fine, but using this on :create throws a nil method, because until the object has been created, it does not have any properties. I've resorted to putting a check in the create action in the controller -

if @chapter.book.user == current_user && @chapter.save

...which is fine, but there's got to be a better way, right?

1

There are 1 answers

4
blelump On BEST ANSWER

In such cases you can use:

     # or just :manage
can [:read, :update, :destroy, :create], Chapter do |chapter| 
  chapter.new_record? || chapter.book.user_id == user.id
end

However, I would simplify it a bit:

can :manage, Chapter, book: { user_id: user.id }