beerlington / classy_enum

A class-based enumerator gem for Rails

Home Page:http://beerlington.com/classy_enum/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add Option to Store Integer Instead of String

SingleShot opened this issue · comments

I would like to be able to order my classy_enums by index in my database queries. Would it make sense to add an option to specify that classy_enums should be persisted as integers? For example:

classy_enum_attr :priority, :persist_as => :integer

Thanks for the suggestion. I'll need to do some research on databases, but it might be possible to do in the DB using an enum type instead of in code. MySQL has an enum type which automatically sorts based on the order they are specific in the column definition. It looks like PostgreSQL's enum type has similar behavior. It seems like enforcing it in the database would be much better than having a bunch of conditional logic to handle both string and integer cases.

I tested it in MySQL and neither Rails nor classy_enum seemed to choke on it being an enum. If you're using a database that supports the enum type, I would recommend this approach. I'll probably play around with it a little and see if there's a way to add some sort of database migration support so you don't have to manually change your DB after.

I think you are saying that if I use PostgreSQL (I do) and migrate my :string to an enum type and order it properly, it will just work? If so - cool! Either way, thanks!

It worked for me in MySQL, but I didn't try PostgreSQL. I'd be interested in hearing how your experience goes with it. I'll probably explore adding some sort of database migration support for the enum type in MySQL and PostgreSQL like:

create_table "alarms", :force => true do |t|
  t.classy_enum "priority", [:low, :medium, :high]
end

I spent a little time exploring ways to build an enum type but decided not to build that into ClassyEnum. There is a gem called enum_column that essentially does what I was thinking, but I didn't want to make it a dependency. I'm going to close this issue, but it is referenced in the readme for anyone who might stumble onto it later.

A little late to the party, but I just wanted to let you know that this works great on PostgreSQL 9.3 and Rails 4.0. I used the migration tips found here: https://coderwall.com/p/azi3ka (see the first comment especially), and all I had to do was modify the line which calls ::PostgreSQLAdapter::OID.alias_type to specify string instead of text. classy_enum worked out of the box. (no need for enum_column gem.)