How to model different users in Rails

痴心易碎 提交于 2019-12-05 00:35:35

问题


Question

I have a User model with authorisation and authentication logic built.

Now I realise I have three different types of users. I want to store different information about each of them.

What is the best way to handle this in Rails?

Thoughts based on current reading

I've looked at STI but from what I've read feel it is inappropriate because I'll end up with a lot of NULL fields in my database.

Ideally I'd like to not duplicate the authentication / authorisation logic for each of the three user types.

Each user will also have different functionality within the application.


回答1:


You can try using polymorphic associations and creating table users with data that all types of users have and putting other data in seperate tables. Railscast epizode covering this topic.




回答2:


There are lots of ways to do this. Here's one approach:

Instead of thinking of different types of users, you could think of roles that a user has.

For example, if a user could be a butcher, baker, or candlestick maker, you could have four tables: users, butchers, bakers, candlestick_makers. The latter three role tables each have a user_id column; they "belong to" the user.

If you need to enforce that a particular user has only one role, you will have to do that in the application (since this database schema would allow multiple roles for a single user).

This method is good if there is a lot of stuff that would belong in those role tables. If not, leaving some NULL columns on the users table probably won't kill you.



来源:https://stackoverflow.com/questions/14763406/how-to-model-different-users-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!