I have a database table for users which contains common fields like password, email etc. And there is also a field named level which defines user level such as member, editor or admin.
There is also some fields that specific for members, editors and admins which others don’t need. So I think I should create separated tables for user types.
And here’s the problem; how should I approach this problem if I want to follow Rails way? Both in terms of database design and associations.
seems you are looking for a role-based authorization system, coupled with specific attributes for each role. One way to achieve this would be with a data model looking like this :
this way, you ensure that all attributes related to a specific role are deleted if that role is removed from the user (by cascade delete).
You will have, though, to ensure that all your attributes models enforce validation rules like this :
if your user can only have one role, you can simplify this by adding a
rolefield on the model, and then write validation rules on optional attributes (thatbelong_toa user) accordingly. Still,the former model offers more potential for future adjustments (creating a new role is just creating a new record).I’m not an expert on this matter though, so you can also continue to seek out inspiration ; the declarative_authorization gem provides an explanation of its data model that you may find interesting, too: