-
Notifications
You must be signed in to change notification settings - Fork 4
Getting Started
This page describes how you can build new tables that use low_card_tables
. Once you've read this page, if you have existing tables you'd like to migrate, see Migrating Existing Tables.
Create the table structure you need in your database:
class MyMigration < ActiveRecord::Migration
def up
create_table :users do |t|
t.string :first_name, :null => false
t.string :last_name, :null => false
...
t.integer :user_status_id, :null => false, :limit => 2
...
end
create_table :user_statuses, :low_card => true do |t|
t.boolean :deleted, :null => false
t.boolean :deceased, :null => false
t.string :gender, :null => false, :limit => 20
t.string :payment_status, :null => false, :limit => 30
end
end
end
In the migration, we simply create the table structure in the most straightforward way possible, with one exception: we add :low_card => true
to the create_table
command on the low-card table itself. The only thing this does is that, once the table has been created, it automatically adds a unique index across all columns in the table — this is very important, since it allows the database to enforce the key property of the low-card system: that there is exactly one row for each unique combination of values in the low-card columns.
The user_statuses
table is called the low-card table itself; the users
table is the referring table.
Create the models:
# app/models/user_status.rb
class UserStatus < ActiveRecord::Base
is_low_card_table
end
# app/models/user.rb
class User < ActiveRecord::Base
has_low_card_table :status
end
And boom, you're done. Any columns present on user_statuses
will appear as virtual columns on User
— for reading and writing, for queries, for scopes, for validations, and so on.
There is one, and only one, significant caveat; read the top of the Caching page for more details. If you do not read this, you may run into problems!
You can see more information about what automatically just works or how to migrate existing tables. You might also want to take a look at the API, options, bulk operations, caching, migrations, or validations.