Rails app,在MySQL中未知的foreign_key列

时间:2012-04-09 20:15:26

标签: ruby-on-rails-3 activerecord mysql2

我在Rails 3应用程序中为遗留数据迁移设置了额外的MySQL数据库。我可以通过这个类轻松连接到它:

class External < ActiveRecord::Base
  self.abstract_class = true
  establish_connection :legacy
end

有两个继承此类的模型:

class LegacySize < External

  set_table_name 'size'
  set_primary_key 'size_id'
  belongs_to :product, :class_name => 'LegacyProduct', :foreign_key => 'product_id'

end

class LegacyProduct < External

  set_table_name 'product'
  set_primary_key 'product_id'
  has_many :sizes, :class_name => 'LegacySize'

end

使用一些简单的ActiveRecord查询看起来很好:

> ls = pp LegacySize.all
  LegacySize Load (0.8ms)  SELECT `size`.* FROM `size` 
[#<LegacySize size_id: 1, name: "small", product_id: 1>,
 #<LegacySize size_id: 2, name: "medium", product_id: 1>,
 #<LegacySize size_id: 3, name: "large", product_id: 1>]

> lp = pp LegacyProduct.all
  LegacyProduct Load (0.7ms)  SELECT `product`.* FROM `product` 
[#<LegacyProduct product_id: 1, name: "shirt", price: 10.0>]

但是当我尝试访问关联时,它会查找列'legacy_product_id'而不是'product_id',我将其定义为size模型中的外键:

> lp = LegacyProduct.find(1).sizes
  LegacyProduct Load (0.9ms)  SELECT `product`.* FROM `product` WHERE `product`.`product_id` = 1 LIMIT 1
  LegacySize Load (0.6ms)  SELECT `size`.* FROM `size` WHERE `size`.`legacy_product_id` = 1
Mysql2::Error: Unknown column 'size.legacy_product_id' in 'where clause': SELECT `size`.* FROM `size`  WHERE `size`.`legacy_product_id` = 1
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'size.legacy_product_id' in 'where clause': SELECT `size`.* FROM `size`  WHERE `size`.`legacy_product_id` = 1

任何人都能看到我做错了什么?

1 个答案:

答案 0 :(得分:0)

foreign_key选项从belongs_to移至has_many :sizes

class LegacyProduct < External
    ...
    has_many :sizes, :class_name => 'LegacySize', :foreign_key => 'product_id'
    ...