ruby on rails - CanCan: set abilities based on controller data or helpers -


so have following setup:

class user < ar   has_many :memberships   has_many :user_groups, through: :memberships   has_many :organizations, through: :memberships end  class membership < ar   belongs_to :user   belongs_to :user_group   belongs_to :organization end  class usergroup < ar   has_many :memberships   has_many :users, through: :memberships   has_many user_groups, through: :memberships end 

so 1 user can e member of several user groups throughout different organizations, i.e. he/she can product manager in organization , article manager , comment manager in organization b.

so in order able ask can? :manage, an_article_instance somehow need have abilities set so:

class ability   if user.is_content_manager_for(currently_selected_organization)     can :manage, article    elsif user.is_admin_for(currently_selected_organization)     can :manage, user, memberships: { organization_id: currently_selected_organization }   end end 

the web interface of backend supposed have select menu user can select on organization he/she wants work on. thinking of maybe storing selected organization in session, since persistent data throughout whole work session.

but access helper method currently_selected_organization (or session directly) in ability (or other) model violate mvc pattern. i've read in several locations not good, etc, etc.

so i'm wondering if there's better/cleaner way of doing this?

ok, figured out different approach. cancan adds current_ability method actioncontroller::base instantiates new ability object , passes current_user object it. 1 can overwrite current_ability method in own controller, ended doing this:

class applicationcontroller < actioncontroller::base   def current_ability     @current_ability ||= ability.new(current_user, organization.find_by(id: cookies[:current_organization])   end end  class ability   include cancan::ability    def initialize(user, currently_selected_organization)     if user.is_admin_for(currently_selected_organization       # ...     end   end end 

this way doesn't break mvc pattern , didn't end including helper modules or hack anything.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -