From: zdennis Date: 2006-10-18T07:19:01+09:00 Subject: Re: Creating enums from ActiveRecord/DB table -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Justin Chan wrote: > Why doesn't the following code work? > > require 'rubygems' > require_gem "activerecord" > > conf = YAML::load(File.open('database.yml')) > ActiveRecord::Base.establish_connection(conf['test']) > > class StuffType < ActiveRecord::Base > has_many :Stuff > end > > class Stuff < ActiveRecord::Base > set_table_name "stuff" > belongs_to :StuffType > def initialize > StuffType.find_all.each do |typ| > class_eval %(#{typ.name} = #{typ.id}) > end > end > end When you create a new Stuff record you aren't guaranteed it has an id, ie, has it been saved to the database or not? Also, ActiveRecord doesn't create new records (when finding records from the database) using the "new" method, so "initialize" never gets it. When do you want your "enum" like behavior to be created, after creation, after update, after find, when the class lods? Also, do you want the relationship to StuffType to be an the instance level or at the class. ie, do you want to say: stuff = Stuff.find( 1 ) stuff.small # assume small is one of your fields in stuff_types or do you want to say: Stuff.small #assume small is one of your fields in stuff_types Zach http://blogs.mktec.com/zdennis -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFFNVcBMyx0fW1d8G0RAlCdAJ4nUvDqvmSLlRB3AW1L134nR3JRUwCeM9lX Jb79dYvk/9RFfUJx+9aNlvk= =8Ihi -----END PGP SIGNATURE-----