In Active Record, how would you map a Customer model onto a legacy tbl_customers table keyed by account_no, with columns like cust_nm?
answer
- override the inferred table name
- primary key is read from the table
- id now means account_no
- alias_attribute for cryptic columns
- 7.2: alias skips custom readers
basics
~10 sSet self.table_name = "tbl_customers", set self.primary_key = "account_no" if the table declares no key, and add alias_attribute :name, :cust_nm; then find, id and URLs use account_no and the aliases work in where and order.
solid answer
~40 s`self.table_name = "tbl_customers"` replaces the inferred `customers`. For the key, Active Record already asks the database which column is the primary key, so if `account_no` is declared as one, `Customer.primary_key` is `"account_no"` without help; write `self.primary_key = "account_no"` when the table declares no key (or to make it explicit). From then on `Customer.find("A-10442")` searches `account_no`, `customer.id` returns that value and `customer_path(customer)` builds `/customers/A-10442`. Because the database does not generate a string key like this, a new customer must be given its `account_no` before `save`. For cryptic columns, `alias_attribute :name, :cust_nm` adds `name`, `name=` and the dirty methods, and `where(name: ...)` and `order(:name)` translate to `cust_nm`. Since Rails 7.2 the alias reads the raw attribute and skips any custom `cust_nm` method; I assume Rails 8.1 here.
code
ruby · 11 linesclass Customer < ApplicationRecord
self.table_name = "tbl_customers"
self.primary_key = "account_no"
alias_attribute :name, :cust_nm
end
customer = Customer.create!(account_no: "A-10442", name: "Ines Duarte")
customer.id # => "A-10442"
Customer.find("A-10442").cust_nm # => "Ines Duarte"
Customer.where(name: "Ines Duarte") # WHERE tbl_customers.cust_nm = 'Ines Duarte'go deeper
Recall the two overrides, self.table_name and self.primary_key, and that id always means the primary key, whatever the column is called.
Explain that Rails reads a declared key from the table, why a string key must be assigned before save, and how alias_attribute reaches into where and order.
Call out the 7.2 alias_attribute change when upgrading a legacy model, and the UnknownPrimaryKey failure on tables or views with no declared key.
Judge when to wrap a legacy schema with per-model overrides versus migrating it to conventions, given the other systems still reading tbl_customers.
## The situation A **utilities-billing** app inherits a database from an older system. Customers live in `tbl_customers`, the key is a string account number such as `A-10442` in `account_no`, and columns are abbreviated: `cust_nm`, `svc_addr`, `created_dt`. Active Record's conventions expect a `customers` table with an integer `id`. Every convention can be overridden **per model**, so the legacy schema can stay as it is. ## Step by step 1. **Point the model at the table.** `self.table_name = "tbl_customers"` replaces the name Rails would infer from the class (`customers`). 2. **Settle the primary key.** Active Record does not blindly assume `id`: it asks the connection for the table's declared primary key. If `tbl_customers` declares `account_no` as `PRIMARY KEY`, `Customer.primary_key` already returns `"account_no"`. Set `self.primary_key = "account_no"` when the table has **no declared key** (common in old schemas and database views) or when you want the mapping visible in the class. 3. **Rename what hurts.** `alias_attribute :name, :cust_nm` gives readable names to cryptic columns. ```ruby class Customer < ApplicationRecord self.table_name = "tbl_customers" self.primary_key = "account_no" alias_attribute :name, :cust_nm alias_attribute :service_address, :svc_addr end ``` ## What changes once the key is account_no - `Customer.find("A-10442")` runs `WHERE account_no = 'A-10442'`. - `customer.id` returns `"A-10442"`: `id` always means **the primary key**, whatever the column is called; `id=` writes it. - `to_param` uses the key, so `customer_path(customer)` builds `/customers/A-10442` and the controller's `Customer.find(params[:id])` keeps working. - **New rows need their key.** An integer `id` usually gets its value from the database; a string account number usually does not. Assign it before saving: `Customer.create!(account_no: "A-10442", name: "Ines Duarte")`, or the database rejects the INSERT. - If the table has **no declared key and you set none**, `Customer.find(...)` raises `ActiveRecord::UnknownPrimaryKey`. ## What alias_attribute does, and what changed in 7.2 `alias_attribute :name, :cust_nm` generates the attribute method family under the new name: `name`, `name=`, `name?`, `name_changed?`, `name_was` and the rest. It also reaches into queries: hash keys in `where(name: "Ines Duarte")` and symbols in `order(:name)` are translated to `cust_nm` before the SQL is built. The Rails 7.2 change matters for legacy code: | | Rails 7.1 and earlier | Rails 7.2 and later (8.1 here) | |---|---|---| | `alias_attribute` reader | called your custom `cust_nm` method | reads the **raw attribute**, bypassing any custom `cust_nm` method | | Old behaviour | default | write `alias_method :name, :cust_nm` | So if the model overrides `cust_nm` (say, to `strip` padding from a `CHAR` column), the alias will **not** run that override any more. ## Related knobs and their owners - **Timestamps on legacy columns**: `alias_attribute :created_at, :created_dt` makes Active Record's automatic timestamping write `created_dt`, because it resolves the timestamp names through the alias table. - **A shared prefix** on every legacy table can be set once with `table_name_prefix` on a base class instead of a `table_name` per model; the naming chain itself belongs to the conventions topic. - **Several key columns** (account number plus invoice number) are a composite primary key, available since Rails 7.1, and work differently: `id` becomes an array. The rule of thumb: override the table name and key once per model, alias only the columns people actually type, and keep `id` meaning "the primary key" everywhere else in the app. ## Checking the mapping in the console Before building screens on a legacy table, confirm what Active Record actually inferred: 1. `Customer.table_name` should print `"tbl_customers"`. 2. `Customer.primary_key` should print `"account_no"`; `nil` means the table declares no key and the model must set one. 3. `Customer.column_names` lists the real columns, so you can see which ones deserve an alias. 4. `Customer.attribute_aliases` shows the aliases the model declared, such as `{"name" => "cust_nm"}`. 5. `Customer.first.id` should return an account number, not `nil`. These five lines catch most legacy-mapping mistakes before they turn into a broken route or a `find` that searches the wrong column.
- tbl_customers has no declared primary key at all and the model sets none. What happens on Customer.find("A-10442")?Active Record asked the database for a key and got none, so `Customer.primary_key` is `nil` and `find` raises `ActiveRecord::UnknownPrimaryKey`. Setting `self.primary_key = "account_no"` fixes the mapping without touching the table.
- The model defines def cust_nm = super.strip and also alias_attribute :name, :cust_nm. What does customer.name return on Rails 8.1?The raw, unstripped value. Since Rails 7.2 `alias_attribute` reads the underlying attribute and bypasses custom methods on the original name. To route through the override, use `alias_method :name, :cust_nm` or define `name` explicitly.
- Claiming the legacy table must be renamed to customers before Active Record can use it.
- Saying self.primary_key is always required, though Rails reads a declared key from the table.
- Expecting customer.id to raise or return nil because the table has no id column.
- Assuming alias_attribute on Rails 8.1 still calls a custom cust_nm reader method.
- Using alias_method to make where(name:) translate to the cust_nm column.
Assumes Rails 8.1; since Rails 7.2 alias_attribute reads the raw attribute and no longer calls a custom method defined for the original column.