我正在使用一个遗留数据库,它为表productfamilia_producto(rake db:schema:dump)提供了以下模式

create_table "producto", primary_key: "barcode", force: true do |t|
  t.string  "codigo_corto",         limit: 16,               null: false
  t.string  "marca",                limit: 35
  t.string  "descripcion",          limit: 50
  t.string  "contenido",            limit: 10
  t.string  "unidad",               limit: 10
  t.float   "stock",                           default: 0.0
  t.float   "precio"
  t.float   "precio_neto"
  t.float   "costo_promedio"
  t.float   "fifo"
  t.float   "vendidos"
  t.boolean "aplica_iva"
  t.integer "otros_impuestos",      limit: 2
  t.integer "familia",              limit: 2,  default: 1,   null: false
  t.integer "id_tipo_producto",     limit: 2,                null: false
  t.boolean "es_perecible"
  t.float   "dias_stock",                      default: 1.0
  t.float   "margen_promedio",                 default: 0.0
  t.boolean "es_venta_fraccionada"
  t.float   "stock_pro",                       default: 0.0
  t.float   "tasa_canje",                      default: 1.0
  t.float   "precio_mayor"
  t.float   "cantidad_mayor"
  t.boolean "es_mayorista"
  t.boolean "estado"
  t.boolean "precio_editable"
end

create_table "familia_producto", force: true do |t|
  t.string "nombre", limit: 32, null: false
end

在我设计的模型中

class FamiliaProducto < ActiveRecord::Base
  self.table_name = 'familia_producto'
  has_many :productos, :class_name => 'Producto', :primary_key => 'barcode', :foreign_key => 'familia'
end

class Producto < ActiveRecord::Base
  self.table_name = 'producto'
  belongs_to :familia_producto, :class_name => 'FamiliaProducto'
end

但当我调用.familia时,producto对象会向我抛出一个数字,而不是FamiliaProducto对象.

2.1.0 :012 >   p = Producto.all[0]
  Producto Load (1.7ms)  SELECT "producto".* FROM "producto"
  => #<Product......
2.1.0 :013 > p.familia
  => 2 

2应该是FamiliaProducto.

推荐答案

您必须使用关联的名称,还需要将外键添加到belongs_to

# Returns a FamiliaProducto object
p = Producto.first
p.familia_producto

# Producto model
belongs_to :familia_producto, class_name: 'FamiliaProducto', foreign_key: 'familia'

# FamiliaProducto model
has_many :productos, class_name: 'Producto', foreign_key: 'familia'

# Returns an integer
p = Producto.first
p.familia

Ruby-on-rails相关问答推荐

Rails 7.1解决冲突的Zeitwerk Inflection规则

Rails 7.1中的覆盖脚手架控制器

Rails6.1|有没有一种方法可以判断哪些关联已经加入到一个范围中?

Trailblazor 操作 -> 集合 :attribute(has_many 通过关联) 与填充器 -> 如何填充 Reform::Form 形式的 slugs 数组?

Rails 7 中的预编译

如何从 New Relic 交易中获取 TraceId?

Rails 7 - has_many_attached 在加载新附件时删除旧附件

无法加载此类文件 -- mysql2/mysql2

设计 token_authenticable 已弃用,有什么替代方案?

Rails - 按连接表数据排序

具有条件的列的计数器缓存?

Rails:参数太少

机械师 vs FactoryGirl - 优点和缺点

Rspec 与 TestUnit

link_to 将参数与 url 一起发送并在目标页面上抓取它们

rails active admin 部署:找不到文件'jquery-ui'

Heroku Postgres 错误:PGError:错误:关系组织不存在(ActiveRecord::StatementInvalid)

Rails 4模块的未初始化常量

使用 Rspec 测试关联的正确方法?

Date.current 和 Date.today 有什么区别?