AnApprentice
AnApprentice

Reputation: 111070

CanCan, setting up a nested resource?

I have the following models:

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

I don't want to do deep nesting, meaning I don't want /group/:id/poll/:id/poll_vote/:id

I want to set it up so my routes:

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

I have poll working, but I can't figure out how to get PollVote working... So far I have:

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

Then in ability.rb

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

What do I use in PollVotes, to have PollVotes check CanCan using Poll?

Thanks

Upvotes: 0

Views: 936

Answers (1)

Jeremy Weathers
Jeremy Weathers

Reputation: 2554

You haven't shown your User <-> Group association, so if User has_and_belongs_to_many :groups then:

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

Of course, you probably want to lock that down to only votes associated with the user.

Edit - here are examples for restricting access to creating and editing poll votes:

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 }

Upvotes: 1

Related Questions