Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up Gender in PostgreSQL

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.

like image 931
tvalent2 Avatar asked Oct 27 '11 02:10

tvalent2


2 Answers

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)
like image 77
wildplasser Avatar answered Oct 23 '22 07:10

wildplasser


An enum seems best: http://www.postgresql.org/docs/current/static/datatype-enum.html

like image 36
mike jones Avatar answered Oct 23 '22 05:10

mike jones