What's the best way to set up a gender field in Rails 3? I'm using PostgreSQL.
I currently have it as a string but am wondering if it would be easier (better?) to set it up as an integer. If so, how would this be done? I want to produce a drop down for it including three values: "Male", "Female", "None of your business".
Sorry for the basic question but I'm curious as to simple, best practices.
This is what domains are for:
DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp;
SET search_path=tmp;
CREATE DOMAIN gender CHAR(1)
CHECK (value IN ( 'F' , 'M' ) )
;
CREATE TABLE persons
( pname VARCHAR
, gend tmp.gender
);
INSERT INTO persons( pname, gend) VALUES ('Alice', 'F') ,('Bob', 'M') ;
INSERT INTO persons( pname) VALUES ('HAL') ;
INSERT INTO persons( pname, gend) VALUES ('Maurice', 'Z') ;
SELECT * FROM persons;
The output:
DROP SCHEMA
CREATE SCHEMA
SET
CREATE DOMAIN
CREATE TABLE
INSERT 0 2
INSERT 0 1
ERROR: value for domain gender violates check constraint "gender_check"
pname | gend
-------+------
Alice | F
Bob | M
HAL |
(3 rows)
An enum seems best: http://www.postgresql.org/docs/current/static/datatype-enum.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With