2

一本书有_许多章节。一个用户有_many 的书。

我正在使用 devise 和 cancancan,并且我希望允许用户:为他们拥有的任何书创建一个章节。我的问题是,一章不属于一本书,直到它存在于能力.rb中 -

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

很好,但是在 :create 上使用 this 会抛出一个 nil 方法,因为在创建对象之前,它没有任何属性。我已经在控制器中的创建操作中进行了检查-

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

...这很好,但必须有更好的方法,对吧?

4

1 回答 1

2

在这种情况下,您可以使用:

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

但是,我会稍微简化一下:

can :manage, Chapter, book: { user_id: user.id }
于 2014-11-13T09:45:25.907 回答