Rails model structure for users

后端 未结 6 752
长情又很酷
长情又很酷 2021-02-04 19:09

I\'m new to rails, and I\'m working on my second rails app.

The app will have different roles for users, but some users will have multiple roles.

Every user of t

6条回答
  •  隐瞒了意图╮
    2021-02-04 19:45

    Although I agree the combination of Devise and CanCan is powerful and works. Let us look at it with a different perspective keeping Association and Delegation in mind.

    Association: In object-oriented programming, association defines a relationship between classes of objects that allows one object instance to cause another to perform an action on its behalf.

    Delegation: Delegation allows the behaviour of an object to be defined in terms of the behaviour of another object. The term 'delegation' refers to the delegation of responsibility. The primary emphasis of delegation is on message passing where an object could delegate responsibility of a message it couldn't handle to objects that potentially could (its delegates).

    With that, what if we design our User and Roles like this. There is no Role class and the User doesn't inherit or specialise a particular class ( Artist, Admin ) instead, all the (Role) class contain the User object and delegate. The way I am thinking and way to implement with Rails is something like this:

    class User < AR::Base
      def user_method
      end
    end 
    
    class Artist < AR::Base
      has_one :user
    
      def artist_method
        # perform an admin task
      end
    end
    
    class Admin < AR::Base
      has_one :user
    
      def admin_method
        # perform an admin task
      end
    end
    

    This role class model is described by Francis G. Mossé in his article on Modelling Roles.

提交回复
热议问题