简体   繁体   中英

How to design database tables for different types of Users?

I'm on a project with Rails, Postgresql and Active Record, where I have Users, that can be either Influencers, or Creators.

The Users have common columns such as email , password , first_name and last_name , but:

  • influencers will have followers , eg_rate , account columns
  • creators will have SIRET_number and specialty columns

How can I design my database so Influencers and Creators are kind of "child" of the Users table? I mean, is it possible to have a db where I can access a User' followers or a User's specialty with one query, or I'll always have to do multiple queries to achieve this? I've tried to create three tables for each, with a foreign key user_id in Influencers table and Creators table. I also tried to add a user_type column to my User table where I pass the values of either "influencer" or "creator", but I'm kind of lost on how to link every tables...

Thank you everyone.

Your approach is right.

You can create a table users with the common columns and add a foreign key to influencers and creators tables.

Then when you need to retrieve the data, you can use ActiveRecord relations to easily fetch data and use ActiveRecord's includes method for relations.

For example:

class Creator < ActiveRecord::Base
   # The relation must be set
   has_one :user
end

# To fetch data anywhere else:
Creator.find_by(SIRET_number: 1234).includes(:user)

If you need to retrieve a creator or influencer by an attribute from related users table, you can use joins :

Creator.joins(:users).where(users: {email: "foo@bar.com"})

Make sure you have the relations set in both User and Creator models. Check out this topic for more info.

By using includes or joins instead of using creator.user you'll avoiding the unnecessary additional query. The downside is the syntax is now longer, you can maybe create your own getters to easily retrieve data instead of writing "includes" everytime.

Also assuming you're not aware of this method, I suggest you to read about the common N+1 problem with Rails & ActiveRecord. The same methods can solve a lot of problems for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM