Rails Migrations and Schemas

Although it is possible to maintain database schemas manually, most Rails developers use the "migrations" facility. This produces the schema.rb file, which offers several approaches for analysis:

  • Parse the code and analyze the sexp

  • Override the methods (eg, create_table) and run the file, collecting information.

  • Introspect the table information, using script/console.

Fortunately, the latter approach seems to work just fine...

Introspection

$ script/console
...
>> ch = Cars.columns_hash; nil
=> nil

>> ch.keys
=> ["id", ...]

>> id = ch['id']
=> #<ActiveRecord::ConnectionAdapters::MysqlColumn:0x180b960
   @default=nil,
   @limit=11,
   @name="id",
   @null=false,
   @precision=nil,
   @primary=true,
   @scale=nil,
   @sql_type="int(11)",
   @type=:integer>

>> Cars.reflect_on_all_associations(:belongs_to)[0]
=> #<ActiveRecord::Reflection::AssociationReflection:0x1a19c84
   @active_record=Cars(id: integer, ...),
   @macro=:belongs_to,
   @name=:car
   @options={},
   @primary_key_name="car_id">

>> Cars.reflections
=> { :car => #<ActiveRecord::Reflection::AssociationReflection:0x1a19c84
       @macro=:belongs_to,
       @primary_key_name="owner_id",
       @active_record=Owners(id: integer, ...),
       @name=:car,
       @options={}>, ...
   }

Although irb is happy to print a serialization of Cars.reflections, to_yaml fails on the @active_record portion (giving "TypeError: can't dump anonymous class Class"). However, inspect works fine:

>> ar = x.active_record
=> Owners(id: integer, ...)

>> puts ar.inspect
Owners(id: integer, ...)
=> nil

Resources

    • Chapter 6: Working with ActiveRecord
    • Chapter 7: ActiveRecord Associations
    • Chapter 8: ActiveRecord Validations
    • Chapter 9: Advanced ActiveRecord


This wiki page is maintained by Rich Morin, an independent consultant specializing in software design, development, and documentation. Please feel free to email comments, inquiries, suggestions, etc!

Topic revision: r5 - 20 Jul 2008, RichMorin
This site is powered by Foswiki Copyright © by the contributing authors. All material on this wiki is the property of the contributing authors.
Foswiki version v2.1.6, Release Foswiki-2.1.6, Plugin API version 2.4
Ideas, requests, problems regarding CFCL Wiki? Send us email