2
votes

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 
2
I had to vote up just for the titleAndrew Cetinic

2 Answers

2
votes

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 
0
votes

I have a couple of suggestions:

Have you tried adding belongs_to :task to the Car and ScheduledInstance Models? This may require that you also add references to the DB.

$ rails g migration add_task_id_to_car task:references
$ rake db:migrate

OR

Have you tried joining on the query?

@task = Task.joins(:instances, :cars, :scheducled_instances).first