Bruce1138
Bruce1138

Reputation: 81

CanCan issues with Rails

I am having a issue with an owner on my rails application not being able to access my Map controller create and show methods using the CanCanCan gem for permissions control.

Here is my ability model with the current config:

class Ability
include CanCan::Ability

def initialize(user)

 if user.role.name == 'owner'

   can :manage, Map, venue_id: user.company.venues.pluck(:id)

 end
end

Output from user.company.venues.pluck(:id):

 Company Load (0.3ms)  SELECT  `companies`.* FROM `companies` WHERE `companies`.`id` = 4 LIMIT 1
   (0.4ms)  SELECT `venues`.`id` FROM `venues` WHERE `venues`.`company_id` = 4
 => [1] 

Here is my Maps Controller Code:

class MapsController < ApplicationController
  before_action :authenticate_user!
  respond_to :html, :json
  load_and_authorize_resource

  def index
    respond_with(@maps)
  end

  def new
   respond_with(@maps)
  end

  def create
    @map = Map.create(map_params)
    if @map.save
      respond_to do |format|
        flash[:notice] = t('floors.created')
        format.json
      end
    else
      flash[:alert] = t('floors.error')
    end
  end

  def show
    respond_with(@map)
  end

  def edit

  end

  def update

  end

  def map_params
    params.require(:map).permit(:alias, :venue_id, :map)
  end

end

Maps belong to venues and has a venue_id. I can get Maps in the Maps index partial on my venue page: Venue Maps

But when I try to create a Map or go to the Map show page I get a CanCan access denied error: CanCan Access Denied

Any ideas on why CanCanCan would allow me to view the Maps index but get access denied when creating or viewing the Map show controller.

Upvotes: 0

Views: 133

Answers (2)

fbelanger
fbelanger

Reputation: 3578

I'm not totally sure about you're #show action, but definitely shouldn't have:

can :manage, Map, venue_id: condition

The reason being that your resource @map = Map.new will not have a venue yet.

It's going to check:

@map.venue_id
=> nil
current_user.company.venues.pluck(:id)
=> [1]
@map.venue_id ==  current_user.company.venues.pluck(:id)
# aka     nil == [1]
=> false

Try the following:

can [:new, :create], Map
can [:show, :edit, :update, :destroy], Map, venue_id: condition

Upvotes: 2

Arisah Ijeoma
Arisah Ijeoma

Reputation: 21

Try explicitly stating the class in the load_and_authorize_resource

load_and_authorize_resource class: "Map"

Upvotes: 0

Related Questions