#88
Virtual Columns with JSON Data Types
7-9-2017
Summary
Continuing from Episode #87, we take a deeper dive into virtual columns in Rails 5.1 and use them to parse JSON Data Types with adding indexes to the virtual column.
7
rails
database
json
7:10
Summary
Continuing from Episode #87, we take a deeper dive into virtual columns in Rails 5.1 and use them to parse JSON Data Types with adding indexes to the virtual column.
7
Resources
MySQL 5.7 Reference - https://dev.mysql.com/doc/refman/5.7/en/create-table-secondary-indexes.html#json-column-indirect-index
Source - https://github.com/driftingruby/088-virtual-columns-with-json-data-types
Episode #87 Virtual Columns in MySQL - https://www.driftingruby.com/episodes/virtual-columns-in-mysql
Summary
Terminalrails g scaffold product name properties:json color:virtual size_id:virtual:index
db/migrate/20170707050032_create_products.rbclass CreateProducts < ActiveRecord::Migration[5.1]
def change
create_table :products do |t|
t.string :name
t.json :properties
t.virtual :color, type: :string, as: "JSON_UNQUOTE(JSON_EXTRACT(properties, '$.color'))"
t.virtual :size_id, type: :integer, as: "JSON_UNQUOTE(JSON_EXTRACT(properties, '$.size_id'))", stored: true
t.timestamps
end
add_index :products, :size_id
end
end
products/_form.html.erb <%= form.fields_for :properties do |builder| %>
<%= content_tag :div, class: :field do %>
<%= builder.label :color, label: 'Color' %>
<%= builder.text_field :color, value: product.color %>
<% end %>
<%= content_tag :div, class: :field do %>
<%= builder.label :size_id, label: 'Size' %>
<%= builder.collection_select :size_id, Size.all, :id, :name, selected: product.size_id %>
<% end %>
<% end %>products_controller.rb def product_params
params.require(:product).permit(:name, properties: [:color, :size_id])
endproducts/show.html.erb<%= @product.color %>
<%= @product.size&.name %>product.rbclass Product < ApplicationRecord
belongs_to :size, optional: true
endsize.rbclass Size < ApplicationRecord
has_many :products
end
t.json doesn't work for me with rails 5.1.4, mysql2 0.4.10, and mariadb 10.2.10. I tried
after migration, schema.rb results in t.text:
I expected t.json. Any ideas?
Wolfgang