Virtual Columns in MySQL

Episode #87 by Teacher's Avatar David Kimura

Summary

In Ruby on Rails 5.1.0, generated virtual column support was added for MySQL and MariaDB. Using generated and stored columns can leverage heavy calculations to the SQL side.
rails database 4:38

Resources

Summary

# Terminal
rails g scaffold users name:string upper_name:virtual name_length:virtual

# 20170703010554_create_users.rb
class CreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table :users do |t|
      t.string :name
      t.virtual :upper_name, type: :string, as: "UPPER(name)"
      t.virtual :name_length, type: :integer, as: "LENGTH(name)", stored: true

      t.timestamps
    end
  end
end