Prev | Current Page 169 | Next

Brad Ediger

"Advanced Rails"

This can be confusing
if you don??™t consider the way the relationship is represented in the schema,
because the foreign_key option defined in Order??™s has_many :line_items statement
actually refers to attributes of LineItem.
114 | Chapter 4: Database
As a final touch, we can set things up so that we don??™t have to worry about the keys
at all in code. Remember that the original reason for using composite keys was to
allow us to use independent sequences on each database server. First, we create
those sequences in SQL when creating the tables. The way we set this up is DBMSspecific;
the PostgreSQL syntax would be:
CREATE SEQUENCE orders_order_id_seq;
CREATE TABLE orders(
node_id integer not null,
order_id integer not null default nextval('orders_order_id_seq'),
(other attributes)
PRIMARY KEY (node_id, order_id)
);
CREATE SEQUENCE line_items_line_item_id_seq;
CREATE TABLE line_items(
node_id integer not null,
line_item_id integer not null default nextval('line_items_line_item_id_seq'),
-- FK to orders
order_node_id integer not null,
order_id integer not null,
(other attributes)
PRIMARY KEY (node_id, line_item_id)
);
When we execute this DDL on all database nodes and enable replication between
them, each node has its own sequence independent of the others. Now we just have
to make sure that each node uses its own node ID. We could either do this in the
database with column defaults (if we can use different DDL for each node) or in
the application with a before_create callback (if each application accesses only one
node).


Pages:
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181