单表继承和has_many问题

时间:2013-08-13 15:12:03

标签: ruby-on-rails ruby activerecord ruby-on-rails-4

我有像

这样的模型
class Group < ActiveRecord::Base
end

class Plant < Group
  has_many :plants_sub_plants, foreign_key: 'plant_id'
  has_many :sub_plants, through: :plants_sub_plants
end

class PlantSubPlant < ActiveRecord::Base
    belongs_to :plant, foreign_key: 'plant_id'
    belongs_to :sub_plant, foreign_key: 'sub_plant_id'
end

class SubPlant < Plant
     has_many :plants_sub_plants, foreign_key: 'sub_plant_id'
     has_many :plants, through: :plants_sub_plants
end

迁移:

class CreateTablePlantsSubPlants < ActiveRecord::Migration
  def change
    create_table :plants_sub_plants do |t|
      t.belongs_to :plant
      t.belongs_to :sub_plant
      t.timestamps
    end
    add_index :plants_sub_plants, :plant_id
    add_index :plants_sub_plants, :sub_plant_id
  end
end

现在当我在下面做的时候,它会爆炸。为什么不调用内连接?

$Plant.first.sub_plants

Mysql2::Error: Unknown column 'groups.plant_id' in 'where clause': SELECT `groups`.* FROM `groups`  WHERE `groups`.`type` IN ('SubPlant') AND `groups`.`plant_id` = 16
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'groups.plant_id' in 'where clause': SELECT `groups`.* FROM `groups`  WHERE `groups`.`type` IN ('SubPlant') AND `groups`.`plant_id` = 16

1 个答案:

答案 0 :(得分:1)

class SubPlant < Plant
     has_many :plants_sub_plants, foreign_key: 'sub_plant_id'
     has_many :plants, through: :plants_sub_plants
end

应该是

class SubPlant < ActiveRecord::Base

 has_many :plants_sub_plants, foreign_key: 'sub_plant_id'
     has_many :plants, through: :plants_sub_plants
end