代码之家  ›  专栏  ›  技术社区  ›  Gaston

钢轨有任何STI

  •  2
  • Gaston  · 技术社区  · 10 年前

    我有一个实例类,使用STI,我有一个子类Car(一个虚拟子类)和ScheduledInstance类。

    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 
    

    当尝试获取任务的汽车或任务的计划实例时,它不起作用。(我在Instance表中有一个type列)

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

    但是,如果我先做Task.first。实例,然后是Task.first。车,没问题。我缺什么?。

    同样根据你的回答,我需要应用哪些更改才能使它与has_many一起工作?

    class Project < ActiveRecord::Base  
      has_many :tasks,      dependent: :destroy
      has_many :instances,  through: :tasks
    end 
    
    2 回复  |  直到 10 年前
        1
  •  2
  •   oreoluwa    10 年前

    我想这个错误可能是由于文件命名。您能否确认您已经:

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

    然后在你的任务中。rb,您应该有:

    class Task < ActiveRecord::Base 
      has_many :instances,          dependent:  :destroy
      has_many :cars
      has_many :scheduled_instances
    end 
    
        2
  •  0
  •   Okomikeruko    10 年前

    我有几个建议:

    你试过添加吗 belongs_to :task Car ScheduledInstance 模型?这可能需要您也向数据库添加引用。

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

    你试过加入查询吗?

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