Ruby-on-rails 带有自定义列名的 Rails 的所属关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25047920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails belongs_to with custom column name
提问by mariowise
I'm working with a legacy database that gives the following schema for the tables productand familia_producto(rake db:schema:dump)
我正在使用旧数据库,该数据库为表product和familia_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
In the models I've this
在模型中我有这个
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
But when I call the .familiathe producto object throws me a number, not the FamiliaProductoobject. Please help!
但是当我调用.familiaproducto 对象时,它会抛出一个数字,而不是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
That 2should be the FamiliaProductoobject.
那2应该是FamiliaProducto对象。
回答by Eyeslandic
You must use the name of the association, also need to add the foreign key to the belongs_to
您必须使用关联的名称,还需要将外键添加到 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

