Noz
Noz

Reputation: 6346

ActiveRecord won't build the right class using STI

I'm using single table inheritance in my application and running into problems building inherited users from an ancestor. For instance, with the following setup:

class School < ActiveRecord::Base

  has_many :users

end

class User < ActiveRecord::Base


  attr_accessible :type #etc...

  belongs_to :school

end

Class Instructor < User

   attr_accessible :terms_of_service
   validates :terms_of_service, :acceptance => true

end


Class Student < User

end

How can I build either a instructor or student record from an instance of School? Attempting something like School.first.instructors.build(....) gives me a new User instance only and I won't have access to instructor specific fields such as terms_of_service causing errors later down the rode when generating instructor-specific forms, building from console will give me an mass-assignment error (as it's trying to create a User record rather than an Instructor record as specified). I gave the example of School, but there are a few other associations that I would like to inherit from the User table so I don't have to repeat code or fields in the database. Am I having this problem because associations can not be shared in an STI setup?

Upvotes: 0

Views: 140

Answers (3)

Noz
Noz

Reputation: 6346

OK it seems part of the problem stemmed from having the old users association inside of my School model. Removing that and adding the associations for students and instructors individually worked.

Updated School.rb:

class School < ActiveRecord::Base

  #removed:
  #has_many :users this line was causing problems

  #added
  has_many :instructors
  has_many :students

end

Upvotes: 0

Valery Kvon
Valery Kvon

Reputation: 4496

And what else:

class School < ActiveRecord::Base
  has_many :users
  has_many :instructors
end

class Instructor < User 
  attr_accessible :terms_of_service # let it be at the first place. :)

  validates :terms_of_service, :acceptance => true
end

Upvotes: 1

Pavel S
Pavel S

Reputation: 1543

You should specify instructors explicitly

class School < ActiveRecord::Base

  has_many :users
  has_many :instructors,:class_name => 'Instructor', :foreign_key => 'user_id'

end

Upvotes: 1

Related Questions