How to get devise to work with multiple models or roles? (Preferably with CanCan and rolify)

前端 未结 1 1942
长发绾君心
长发绾君心 2021-01-21 17:15

Using devise, what is the best way to have multiple models or roles? Here are the models or roles I need in my app:

-Author: can upload content to the site
-Cust         


        
1条回答
  •  旧巷少年郎
    2021-01-21 18:06

    From your question, I understand you've already "dived" into rolify and cancan, so I'll focus on assigning roles.

    You typically create different roles in your seeds.rb file, with something like

    [:admin, :author, :customer].each do |role|
      Role.find_or_create_by_name({ name: role }, without_protection: true)
    end
    

    You assign the :admin role immediately when you create yourself as administrator, also in the seeds.rb file, using

    user.add_role :admin
    

    For your other roles, you assign them "when it's appropriate", exactly as you describe. When a user clicks the Authors link, and proceeds, this triggers some action in some controller. It is there that you assign this role to that user, by using the same

    user.add_role :author
    

    You can also assign roles, connected to certain objects only. E.g. an author is author for only the documents he creates himself. In that case you don't want to assign a "general" author role, but you will assign it like

    user.add_role :author, document
    

    in the controller's create action, together with saving the created document. Alternative for this kind of assignment is to do it in a callback from your model.

    More questions? Just ask!

    0 讨论(0)
提交回复
热议问题