0

If Users --> students // employee (single table inheritence), and they both belong to a Organization --> School // Work (single table inheritance), what is the proper way to write the association? I put the organization_id into the User class, and wrote the belongs to /has many in the respective subclasses, but when I call User.school, I get "nil", even though he has an organization_id = 1.

user.rb

class User < ActiveRecord::Base
  attr_accessible :email, :name, :password, :organization_id, :type
end

student.rb

class Student < User
  belongs_to :school
end

employee.rb

class Employee < User
  belongs_to :company
end

organization.rb

class Organization < ActiveRecord::Base
  attr_accessible :name
end

school.rb

class School < Organization
  has_many :students
end

company.rb

class Company < Organization
  has_many :employees
end
im so confused
  • 2,091
  • 1
  • 16
  • 25

2 Answers2

0

I would strongly advise you to not use single-table inheritance. What benefits do you get from it? Students and Employees are different things, as are Schools and Companies. They should be separate tables. It will make your life so, so much simpler in the long-run. And if you don't use single-table inheritance, this problem goes away too.

Russell
  • 12,261
  • 4
  • 52
  • 75
0

The User class does not define the school association and knows absolutely nothing about the Student class. So you can't expect User.school to work. You can expect Student.school to work since this is what your code defines.

What STI does form the perspective of columns, it just adds a type string column which shows which sub-type of model the record maps to.

You also might rethink how you model your data. A student belongs to a school, but a user might also belong to a company or maybe two schools.

Andreyy
  • 511
  • 2
  • 11