Rails model structure for users

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

    I think you don't have to create different models because you don't have specific fields for each one. So you just have to set the "role" of each User. Two options : create a role table or add a role field in the table User. Both solutions work, the second is more flexible but less optimized.

    But, in your particular case, you don't have a complex role management so you can find a simpler solution. If all of your users are artists you don't have to specify this in your code, it's contained in the implicit description of what a user is. So you just have to save if a user is an admin or not and I think the best solution is to create a boolean field "is_admin".

    After that you will have to create some before_filter in your protected controllers, like that :

    before_filter => :authorize, :only => :new, :edit, :create, :update, :destroy
    
    def authorize
      redirect_to :root if not current_user.is_admin?
    end
    

    And you can have simple requests like that :

    @artists = User.all
    @moderators = User.where(:is_admin => true)
    

    If you look for a more complete authorization system you can check this small gem : https://github.com/ryanb/cancan

    But I think it's not the case for the moment. If you have a simple problem look for a simple solution !

提交回复
热议问题