# Can't dynamically create an Acitve::Record object

**URL:** <https://discuss.rubyonrails.org/t/cant-dynamically-create-an-acitve-record-object/1873>\
**Category:** rubyonrails-talk\
**Created:** [September 19, 2006, 5:32pm UTC](https://discuss.rubyonrails.org/t/cant-dynamically-create-an-acitve-record-object/1873 "2006-09-19T17:32:45Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Andrew\_Stone](https://avatars.discourse-cdn.com/v4/letter/a/b9bd4f/32.png) [@Andrew\_Stone](https://discuss.rubyonrails.org/u/Andrew_Stone)\
**Post date:** [September 19, 2006, 5:32pm UTC](https://discuss.rubyonrails.org/t/cant-dynamically-create-an-acitve-record-object/1873/1 "2006-09-19T17:32:45Z")

</div>

I’m not sure what’s wrong with the code you listed, but here’s a module I use to create dynamic active record objects.

module Stone module Dynamic class \<\< self def klass(table\_name)

```
    tname = class_name_from_table(table_name)
    #see if it has already been defined
    const_missing(tname)
  rescue NameError
    define_klass(table_name)
  end

  def objeck(table_name)

    klass(table_name).new
  end

  private
    def class_name_from_table(table_name)
      Inflector.camelize(table_name)
    end

    def define_klass(table_name)

      tname = class_name_from_table(table_name)
      class_def = <<-end_eval
        class #{tname} < ActiveRecord::Base
          set_table_name('#{table_name}')
        end
      end_eval

      eval(class_def, TOPLEVEL_BINDING)
      const_get(tname)
    end
end

```

end end

Hope this is of some use, andy
