Rails belongs_to with custom column name

You must use the name of the association, also need to add the foreign key to the belongs_to

class Producto < ApplicationRecord
  belongs_to :familia_producto, class_name: 'FamiliaProducto', foreign_key: 'familia'
end
class FamiliaProducto < ApplicationRecord
  has_many :productos, class_name: 'Producto', foreign_key: 'familia'
end
p = Producto.first

# Returns a FamiliaProducto object
p.familia_producto

# Returns an integer
p.familia

Leave a Comment