2011-07-27 72 views
0

我有以下型号:CanCan,建立一个嵌套资源?

Group (id) 
Poll (id, group_id) 
PollVote (id, poll_id) 

我不想做深嵌套,这意味着我不希望/组/:ID /调查/:ID/poll_vote /:ID

我想设定,让我的路线:

/group/:id 
/poll/:id 
/poll/:id/poll_vote/:poll_vote_id 

我有民意调查工作,但我无法弄清楚如何获得PollVote工作......到目前为止,我有:

class PollVotesController < ApplicationController 

    # Authorization w Devise & CanCan 
    before_filter :authenticate_user! # Devise, signed in users only 
    load_and_authorize_resource :poll # CanCan 
    load_and_authorize_resource :poll_vote, :through => :poll 

    # We need to pass along the wall 
    def current_ability 
     @current_ability ||= Ability.new(current_user, @poll.group_id) 
    end 

然后在ability.rb

can [:manage], Poll do |poll| 
    This returns TRUE is the user is a group member of the poll 
end 

有什么值得我PollVotes使用,有PollVotes惨惨使用轮询检查?

感谢

回答

1

您还没有显示您的用户< - >集团的关联,因此,如果User has_and_belongs_to_many :groups则:

can :manage, [ Poll ] { |poll| user.groups.include?(poll.group) } 

当然,你可能要锁定下来只与相关票用户。

编辑 - 这里是一个例子,从而限制对创建和编辑投票表决访问:

can :read, PollVote # not needed if you have e.g. can :read, :all 
can :create, [ PollVote ] { |poll_vote| user.groups.include?(poll_vote.poll.group) } 
can [ :edit, :destroy ], [ PollVote ] { |poll_vote| poll_vote.user_id == user.id } 
+0

杰里米,感谢这个...我很困惑什么是ability.rb我还需要一个能:管理,PollVote? – AnApprentice

+0

另外,我如何将它锁定为仅与用户相关的投票?非常感谢,CanCan – AnApprentice

+0

@AnApprentice:我在答案中添加了更多示例。 –