How to model different users in Rails

2020-06-18 09:39发布

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.

2条回答
等我变得足够好
2楼-- · 2020-06-18 10:08

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.

查看更多
Luminary・发光体
3楼-- · 2020-06-18 10:13

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.

查看更多
登录 后发表回答