3

Recently I converted from django development to fulltime rails work, it is a fairly small shop and I'm picking things up from books and on my own as I go.

Last week I was hit with a major blow to my mental model when I learned that rails' models do not mirror the content in the database.

See example of the differences: http://www.peterkrantz.com/2009/rails-grails-django-models/

What I'm curious of, is how do I continually modify a model to support new data types and relations?

Also, is there a way to have all of the attributes in a table for a specific class shown in the models file?

Thanks

Chris King
  • 63
  • 7

2 Answers2

5

I think migrations are what you are looking for.

If you want all of the columns shown in the model file, use the annotate gem

Marek Příhoda
  • 11,108
  • 3
  • 39
  • 53
  • So the workflow is: 1. Design new schema 2. Implement it with a migration 3. Use annotate to keep comments up-to-date that describe the schema being used – Chris King Dec 20 '11 at 17:09
  • @Chris Yes. There's also a note on the [gem's page](https://github.com/ctran/annotate_models) that says "If you install annotate_models as a plugin, it will automatically adjust your rake db:migrate tasks so that they update the annotations in your model files for you once the migration is completed." But I just run `annotate --exclude tests,fixtures --position before` from time to time – Marek Příhoda Dec 20 '11 at 17:26
1

This depends on an ORM you use. While ActiveRecord indeed fetches schema from the database, Mongoid offers to annotate your models. Here's one of models from my current project:

class DailyStat

  include Mongoid::Document

  identity :type => String

  field :app_id, :type => Integer
  field :date, :type => DateTime

  field :stats, :type => Hash
  field :totals, :type => Hash
  field :counts, :type => Hash
end

This is so because of schemaless nature of MongoDB. Without such declarations, all fields would have dynamic type (String by default). And declarations help to enforce types.

Also, with MongoDB you have no migrations and annotate gem won't help here.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367