Reputation: 3199
I was wondering how can I create different user roles depending on which part of the site user registers? For example, I have three user types. One is admin, another is regular user and third one is moderator.
I have the following table:
create_table "users", force: true do |t|
t.string "username"
t.string "email"
t.string "role"
t.string "password"
end
Inside "role" column I would save one of the following strings: "admin", "regular" or "moderator".
I have already created my authentication system with the help of Michael Hartl's Ruby on Rails Tutorial. Also, I watched railscasts episode #189 Embedded Association where there is a really nice approach of handling multiple user roles.
The problem is that on video user roles are chosen during registration and I don't want user to see user roles. I have two sections of the site. If user registers through one section he will have a role "regular" and if he registers through another section he will have role "moderator". Role "admin' would of course be set differently.
It could be done if I pass parameter "role": "moderator" or "role": "regular" but that doesn't seem to me as the safe option because it would be visible to users and they can easily pass some other parameter there. For example regular users who want to harm the site could pass "role": "moderator".
Thank you for your advices :)
Upvotes: 1
Views: 1368
Reputation: 1008
I would go with CanCan and Rolify and it's very well documented here: https://github.com/EppO/rolify/wiki/Tutorial. There are also some awesome Railscasts about it.
This way you can add all users the same way and simple add a role depending on the page the user chose to sign up from (why is that secure?). I assume that you have some internal sites only accessible by you to add admin and editors?
Now you can use request.original_url and add a switch statement to do something like: current_user.add_role "admin"
Of course you can also use your approach and just update the user record with: current_user (or user you are about to create in your user controller) and do a user.role = "admin" user.save
Hope it helps!
Upvotes: 1