Search code examples
ruby-on-railsruby-on-rails-4has-manysingle-table-inheritancesti

Rails has_many STI


I've trying to implement a STI on rails 4, but I can't make it work, I've search a lot of results but none worked. Here is the problem:

I have an instance class, using STI I have a subclass Car (a dummy subclass) and ScheduledInstance class.

class Instance < ActiveRecord::Base
  belongs_to :task
end 
class Car < Instance end 
class ScheduledInstance < Instance end 

class Task < ActiveRecord::Base 
  has_many :instances,          dependent:  :destroy
  has_many :cars
  has_many :scheduledinstances
end 

When trying to get a task's cars or a task's scheduledinstances, it doesn't work.(I have a type column on Instance table)

Task.first.cars
  Task Load (0.8ms)  SELECT  "tasks".* FROM "tasks"  ORDER BY "tasks"."id" ASC LIMIT 1
NameError: uninitialized constant Task::Car

however, if I do Task.first.instances, and then Task.first.cars, it works ok. What I am missing?.

Also based on your answer, what changes do I need to apply to make it work with a has_many through?

class Project < ActiveRecord::Base  
  has_many :tasks,      dependent: :destroy
  has_many :instances,  through: :tasks
end 

Solution

  • I'm thinking the error may be due to file naming. Could you confirm that you have:

    # models/car.rb
    class Car < Instance
    end 
    
    # models/scheduled_instance.rb
    class ScheduledInstance < Instance
    end 
    

    Then in your task.rb, you should have:

    class Task < ActiveRecord::Base 
      has_many :instances,          dependent:  :destroy
      has_many :cars
      has_many :scheduled_instances
    end