Rails model structure for users

后端 未结 6 816
长情又很酷
长情又很酷 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:43

    If you need to have code that's specific to and role or such as an admin or moderator one other solution would be to create a base User model that all the other classes inherit from. You can then create an Admin class and a Moderator class that inherit from the User model. This would mean you can avoid constantly checking the users role in your code e.g. current_user.do_some_admin_thing if current_user.is_admin?. Your classes would look something like this

    class User < ActiveRecord::Base
      # base user methods in here
    end
    
    class Moderator < User
      def do_moderator_thing
        # perform a moderator task
      end
    end
    
    class Admin < Moderator
      def do_admin_thing
        # perform an admin task
      end
    end
    

    In this instance the User class has the most basic privileges, moderators can do everything users can plus the moderator specific methods and admins can do everything users and moderators can plus the admin specific methods.

    All the different user roles would use the same table in the database but your concerns are neatly separated into classes which avoids excessive conditionals through your code checking what role the user is all the time.

    Creating new users would be straightforward also Admin.new :name => 'bob' the Admin class then takes care of how a user is defined as an admin which provides a nice interface where you don't need to know the inner workings of the role system to interact with users.

提交回复
热议问题