All threads / Moving from STI to roles

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Moving from STI to roles

Daniel Weaver asked in Rails

Finding it tricky to move from STI (Single Table Inheritance) to user roles because associations between the various user roles to other resources mean different things to different user types.

Teacher and Family models both inherit from User table. Separately we also have Student and Lesson resources.

Teachers teach (has_many) students, so when I call @teacher.students I get all the students taught by that teacher. Likewise, a family has_many students, so when I call @family.students I get all the student who belong to that family.

Similar for lessons - teachers make lessons and families view their students lessons. When I call @teacher.lessons I get a list of all lessons created by that teacher. When I call @family.lessons I get a list of all lessons created for studnets that belong to that family.

So if I were to get rid of STI and just use one User model, what would calling @user.students or @user.lessons return?

I could create some new association names and specify a foreign key, something like:

class User < ActiveRecord::Base

 # for Teachers
 has_many :students, foreign_key: "teacher_id", class_name: "Student"
 has_many :lessons, foreign_key: "teacher_id", class_name: "Lesson"

 # for Families
 has_many :kids, foreign_key: "family_id", class_name: "Student"
 has_many :kids_lessons, foreign_key: "family_id", class_name: "Lesson"

  ...

Is this a reasonable way to go or is there another more Rails-y way to do this?

Found this SO answer suggesting using the strategy pattern to give methods different behaviour based on the user role. Looks very interesting but quite complex.

https://stackoverflow.com/questions/38669599/multiple-role-based-classes-inherited-from-user-class-rails-4

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 33,399+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.