Question

I got Partenaires resources who had many Agences, and User who had many Agences.

I want to restrict access for each Partenaire with Cancan & Rolify.

The only hack i found to do it, is to evaluate the array size of user.agence_ids & partenaire.agence_ids and if it's upper or equal at 1 so the user can access to the Partenaire.

I did custom action to filter my Index view into my Partenaires_controller.

Is it possible to grant access to the User if the Partenaire and the user got at least one Agence in common?

class Ability
 include CanCan::Ability

 def initialize(user)
  # Define abilities for the passed in user here. For example:
  #
    user ||= User.new # guest user (not logged in)
   if user.has_role? :admin
     can :access, :rails_admin # grant access to rails_admin
     can :dashboard # grant access to the dashboard
     can :manage, :all
   elsif user.has_role? :user
     can [:index, :edit, :update, :show, :new, :create], Partenaire do |partenaire|
       (user.agence_ids & partenaire.agence_ids).size >= 1
     end
   end
 end
end

Partenaires_controller.rb

def index
 flash[:ville] = params[:id]
 @ville = flash[:ville]
 #Permet l'affichage des partenaire sur un tri de ville
 if current_user.has_role? :user
   if params[:id] == 'ALL' || params[:id].nil?
   @partenaires = @search.includes(:agences).where(['agences.id IN (?)', current_user.agence_ids]).order(:ville, "partenaires.nom asc")
   elsif params[:id] != 'ALL' && !params[:id].nil?
   @partenaires = @search.where(:ville => params[:id]).order("ville, nom asc").where(:id => current_user.agence_ids)
   end
 elsif current_user.has_role? :admin
  if params[:id] == 'ALL' || params[:id].nil?
  @partenaires = @search.order("ville, nom asc")
  elsif params[:id] != 'ALL' && !params[:id].nil?
  @partenaires = @search.where(:ville => params[:id]).order("ville, nom asc")
  end
end

User.rb

class User < ActiveRecord::Base
 rolify
 has_and_belongs_to_many :agences
end

Agence.rb

class Agence < ActiveRecord::Base
 has_and_belongs_to_many :users
 has_and_belongs_to_many :partenaires

Partenaire.rb

class Partenaire < ActiveRecord::Base
 has_and_belongs_to_many :agences
Was it helpful?

Solution

found the solution on another SO post.

 (user.agence_ids & partenaire.agence_ids).present?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top