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?
In such cases you can use:
However, I would simplify it a bit: