DEV Community

Cover image for Database setup and associations for simple quiz app
Milan Zivkovic
Milan Zivkovic

Posted on

Database setup and associations for simple quiz app

Intro

Building a simple quiz application started with a blank diagram and cognition that my SQL knowledge is fading (if I ever had any). I'll just say that I had to refresh on lectures on join tables (inner join tables to be precise).

What you will find in this blog

Here you will find the database diagram and model associations. I hope it will give you guidance for your quiz application. Worth mentioning is that backend side was created in Rails with --api flag (generators will not create views folder, frontend side will be written separately )
Database scheme

Models

  1. Quiz
  2. Question
  3. Option
  4. User
  5. Take
  6. Response

Model Associations

Quiz

has_many :questions
has_many :takes
has_many :users, through: :takes
Enter fullscreen mode Exit fullscreen mode

Question

belongs_to :quiz
has_many :options
has_many :responses
Enter fullscreen mode Exit fullscreen mode

Option

belongs_to :question
has_many :responses
Enter fullscreen mode Exit fullscreen mode

User (with basic validations)

has_many :takes
has_many :quizzes, through: :takes
validates :username, presence: true
validates :email, presence: true
validates :email, uniqueness: true
Enter fullscreen mode Exit fullscreen mode

Take

belongs_to :user
belongs_to :quiz
has_many :responses, dependent: :destroy

Enter fullscreen mode Exit fullscreen mode

Response

belongs_to :take
belongs_to :option
belongs_to :question
Enter fullscreen mode Exit fullscreen mode

Summary

Having Takes table as a join table between Users and Quizzes will give as an option that user can retake the quiz as many times as he/she wants.
Each response will belong to take, question and option. Here we can distinguish responses for the same question with the same option selected but that happens it different takes.

Top comments (0)