Reputation: 8827
How do you model user roles when the roles have different associations with external models?
I have two roles, teacher and parent. teachers have an associated school, parents don't. It makes it hard to model teachers and parents in a single model.
I would prefer not to model them separately as their state (fields) are the same, and they both have a "has and belongs to many" (HABTM) association with children.
I have tried using single table inheritance (STI) which solved my immediate problem, but ultimately caused a great deal more problems. I was hoping for a "composition over inheritance" solution.
Upvotes: 2
Views: 103
Reputation: 1392
if you want to keep one class, conditional relations could help you
class User < AR
has_one :school, conditions: { role: 'teacher' }
end
Still kinda quirky, but better than STI
Upvotes: 2
Reputation: 54902
A conditional has_one relation could work for you:
class Role < ActiveRecord::Base
has_one :school, conditions: { name: 'Teacher' }
belongs_to :user
And then you should be able to do:
user = User.first
user.role # let's say he is a Teacher
user.role.school # => should return the school
Some documentation about has_one: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_one
Upvotes: 2