Is it better to have roles as a column on my users table, or do it through join tables (Roles & Assignments)? - Rails 3

StackOverflow https://stackoverflow.com/questions/4623599

Question

You can see my models here:

https://gist.github.com/768947

Just to explain what is happening, I have a few models. At the core of my app, there are: projects, stages, uploads, comments, users. Then there are roles & assignments to manage user authorization.

I am doing this with the plugin declarative_authorization & devise for login.

So the first question is, is it better to just add a column of 'Roles' to my user model/table and store the roles for each user there? If I have a user that has multiple roles, then I can just store all the roles as an array and cycle through them as needed.

Or is it better to do it like I have it setup now, where I use two separate tables and a bunch of joins to setup the assignments? I only have 4 roles: designer, client, admin, superuser.

Better in the sense that it is 'less expensive' from a computing resources standpoint to do each query with the column, than with the joins or is the difference not that significant?

I guess, the root of my question is...right now if I want to get a project assigned to the current_user I simply do current_user.projects.each do |project| and cycle through them that way. This is after I have done: @projects = current_user.projects in the projects controller. The same applies for all my other models - except Users & Roles.

However, if I wanted to find a user with role "client", it becomes convoluted very quickly. Or am I overcomplicating it?

Any help would be appreciated.

Was it helpful?

Solution

I think it's better to have user and role tables that are separate. It's a many-to-many relationship, because a user can have many roles and many users can have the same role. You'll need a JOIN table (e.g. user_role) to do that. I'd recommend three tables. Of course you'll have primary keys for both user and role; the user_role table will have two columns, one for each primary key, and foreign key relationships to their respective tables.

So now if you want all users with the role "client", it's an easy JOIN between user and user_role. If you want a particular user's roles, you'll need to JOIN the three tables.

I would not recommend an array of roles in user. It goes against first normal form.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top