首页 > 解决方案 > 非标准键引用的导入任务

问题描述

这样的两个类的关联,

class Available < ActiveRecord::Base
  belongs_to :structure, class_name: 'Structure', foreign_key: 'product_code'

class Structure < ActiveRecord::Base
  self.primary_key = 'product_code'

在 rake 任务下导入时会产生后果

  begin
   Structure.create(
      product_code: row[0],
      destination: row[1],

创建以 id 作为 product_code 的记录,以及 product_code 属性本身 #<Structure id: "CAN752500", product_code: "CAN752500", destination: [...]

我注意到,在未在Structure模型上定义关联的原始导入中,属性id具有其预期值;在模型中指定后self.primary_key,数据库中的值id被该product_code值覆盖。

更新的问题 这个期望的目标是,保持structure.id为整数,同时具有product_code功能上的关联。
如何定义?

标签: ruby-on-railsassociationsrails-activerecord

解决方案


推荐阅读