Search code examples
ruby-on-railsrubyrails-activerecord

How to define model relationships for this Rails app for physiotherapists?


I'm a Ruby on Rails beginner trying to build my first real-life Rails app.

The idea is as follows:

The app shows an overview of exercises. Each exercise has a category:string, bodypart:string, instructions:text and an image (will add this using the Paperclip gem). Then there are patients. Each patient has a name:string and email:string. Finally there are exercise plans. Each exercise plan has a name:string and will contain exercises from the exercise overview.

As a user of the app (physiotherapist) I can select exercises from the overview and e-mail them to a patient in the form of a PDF (will implement this using the Prawn gem). When selecting the exercises the user (physiotherapist) should be able to enter 'repetitions' or 'duration' per exercise. This should be added to the exercise plan and printed to the PDF.

How can I best define the model associations in ActiveRecord?


Solution

  • I would start with something like this:

    class Exercise < ActiveRecord::Base
      has_many :exercise_plans
    end
    
    class Patient < ActiveRecord::Base
      has_many :exercise_plans # or perhaps just `has_one`?
    end
    
    class ExercisePlan < ActiveRecord::Base
      belongs_to :patient
      has_and_belongs_to_many :exercises
    end
    

    Tables you will need on the db: exercises, patients, exercise_plans, exercise_plans_exercises. The last just hold the association between plans and exercises and only need references to exercise_plan_id and exercise_id