Skip to content

CASE: Natural key

maiha edited this page Feb 21, 2018 · 1 revision

In this example, we treat date field with DATE type as natural key.

mysql

mysql> describe batch_runs;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| date  | date     | NO   | PRI | NULL    |       |
| at    | datetime | NO   | MUL | NULL    |       |
| pct   | int(11)  | NO   |     | NULL    |       |
| click | int(11)  | NO   |     | NULL    |       |
| log   | text     | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+

model

BatchRun corresponds to batch_runs table where date DATE is used as a natural key. So, we define ymd method as a resource id of CRUD operations.

class BatchRun < Granite::ORM::Base
  adapter mysql

  primary date : Time, auto: false
  field at    : Time
  field pct   : Int32
  field click : Int32
  field log   : String

  def ymd
    date.to_s("%Y-%m-%d")
  end
end

NOTE: The official Granite can't handle natural keys. So we are using maiha fork.

  • github: maiha/granite-orm

controller

class BatchController < ApplicationController
  include ActiveScaffold(BatchRun)

  active_scaffold do |config|
    config.id = "ymd"
    config.label = "Batch Job"
    config.columns = ["ymd", "at", "pct", "click", "log"]
    config.columns["ymd"].label = "Date"
    config.action_links["list"].label = "Back"

    config.list.columns["log"].truncate = 13
    config.list.paging.order  = "date DESC"
    config.list.paging.limit  = 7

    config.show.label = "Batch(%s)"
    config.show.action_links = ["list", "edit"]

    config.edit.label = "Batch(%s)"
    config.edit.action_links = ["list", "show"]
  end
end

list

list

show

show

edit

edit

Clone this wiki locally