Archive

Posts Tagged ‘rails’

Migrations: Did they mature with Rails 2.1.#

September 30, 2008 Gaurav Sohoni 4 comments

With the new face of Rails (Rails 2.1 and beyond), came the change in the way migrations used to work.
So lets see some of the changes that went into migrations (that is when Rails was 1.2.3)… the then and now changes …

First of all, serial numbers for migrations are gone and they have made way for the UTC based names for
the migrations. So earlier (pre Rails 2.1 era) if one created migration scripts, they used to get their
names serially like…


001_create_books.rb
002_create_shelves.rb


whereas now the names have the UTC timestamps on them …

20080601000001_create_books.rb
20080601000002_create_shelves.rb

With this new change rake db:migrate could apply all migrations that had not yet gone into database (as now
all migrations run and add an entry into the database migration table). Because of this the issue with the earlier version of migrations was taken care of i.e old migrations heavily used to rely on once single entry to run the migrations. If you somehow happened to screw the version number, u ended up getting failed migration errors.

Along came one more functionality which now lets run the up and down functions for a particular migration.

$ rake db:migrate:up VERSION=20080601000002
$ rake db:migrate:down VERSION=20080601000002

rake db:migrate:up or rake db:migrate:down let you go up or roll back a particular migration’s changes.

The other change was the name of the table that stored the migration information. In earlier version of
rails, it used to be ’schema_info’ which gave way to ’schema_migrations’. So I would suggest not to look
for the earlier name in case you got your application migrated from Rails 1.2.# to Rails 2.1.#.

We also got rid of specifying

t.column <attribute_name> <data_type>
for the attributes and

it got reduced to

t.<data_type> <attribute_name>

which would look something like this in the new migration…

class CreateBooks < ActiveRecord::Migration
  def self.up
    create_table :books do |t|
      t.integer :code, :null => false
      t.string :name
      t.string :author_id ... for the author's sake...
      t.timestamps
    end
  end


  def self.down
    reverse the gears ...
  end
end

To add to this, timestamps came into existence which was a required addition so that we could save
some keystrokes and bid goodbye to

t.column created_at
t.column updated_at

So those were some of the changes cum additions ….
To go ahead with, lets see the cycle of migration …

Now with the new mmigrations, when they are run, this is what happens …

1. Table ’schema_migrations’ is created if that does not exist.
2. For every migrations that runs successfully, an entry is created in the schema migrations table.
3. The leading part of the migration filename gets stored into the table.
     For eg. 20080601000001 gets saved when 20080601000001_create_books.rb runs and updates the database.
4. New migrations run when an entry is not found in the migrations table.

So now if you want to force and roll your database to a specific version, you supply the VERSION= parameter

$ rake db:migrate VERSION=20080601000002

If that version happens to be greater than those already in, the migrations will be applied. But in case the
version number is lesser than those in the migrations table, than Rails undoes the changes and self.down comes into play and thus migrations run in reverse direction to undo changes to the version that was specified.

One good thing which most of us must be missing and which is gone with arrival of the new migrations is the shorter version numbers for the migration files.

Earlier we could do something like

$ rake db:migrate VERSION=2

which has become this now

$ rake db:migrate VERSION=20080601000002

So I bet it is not so easy to remember the exact 14 character version number but I guess as long as we have Ctrl C n Ctrl V, it wont be much of a problem ;)

So to end or startup with, I think they did mature just like other things that matured with time …
Rails included :)

Time for me to migrate to a new blog post .. till then keep migrating the new way …

Migrations

August 12, 2008 Gaurav Sohoni 6 comments

I am back on track .. track of writing something new here…
and this time it is Migrations .. Rails Migrations ..

As you must be knowing (u all Rails enthusiasts) that migrations allow
you to make changes to your database schema. In doing so, you also get the
facility of moving from version x to y of your database.

So this time I was required to add a column to my already existing model.
So I went ahead and did something like this …

def self.up
  add_column :media, :category_name, :string
  muvee = Media.find_by_name('whoami')
  muvee.update_attributes :category_name => 'action'
end


When I ran this migration, the new column got added to the table but the
migration did not update the data in the table.

I reran.. thinking I missed something but nothing happened.

After a while I came across something and added it to the migration code. This time

it did add the column along with the data.

def self.up
  add_column :media, :category_name, :string
  muvee = Media.find_by_name('whoami')
  FileType.reset_column_information # This was added ...
  muvee.update_attributes :category_name => 'action'
end

What ‘FileType.reset_column_information’ does is that it makes the new schema change
available to the model as it resets the column information ( w/ the information about the new column). Thus the changes become available for the new data to be inserted properly.

Hope this information helps someone out there in case such situation arises.

Cheers !!!

Categories: databases, rails Tags: , , ,

Rake Tasks

May 21, 2007 Gaurav Sohoni 1 comment
rake cache:clear                      # Clears all cached pages
rake db:bootstrap                     # Loads a schema.rb file into the database and then loads the initial database fixtures.
rake db:bootstrap:copy_default_theme  # Copy default theme to site theme
rake db:bootstrap:load                # Load initial database fixtures (in db/bootstrap/*.yml) into the current environment's database.  Load specific fixtures using FIXTURES=x,y
rake db:fixtures:load                 # Load fixtures into the current environment's database.  Load specific fixtures using FIXTURES=x,y
rake db:migrate                       # Migrate the database through scripts in db/migrate. Target specific version with VERSION=x
rake db:schema:dump                   # Create a db/schema.rb file that can be portably used against any DB supported by AR
rake db:schema:load                   # Load a schema.rb file into the database
rake db:sessions:clear                # Clear the sessions table
rake db:sessions:create               # Creates a sessions table for use with CGI::Session::ActiveRecordStore
rake db:structure:dump                # Dump the database structure to a SQL file
rake db:test:clone                    # Recreate the test database from the current environment's database schema
rake db:test:clone_structure          # Recreate the test databases from the development structure
rake db:test:prepare                  # Prepare the test database and load the schema
rake db:test:purge                    # Empty the test database
rake deploy                           # Push the latest revision into production using the release manager
rake diff_from_last_deploy            # Describe the differences between HEAD and the last production release
rake doc:app                          # Build the app HTML Files
rake doc:clobber_app                  # Remove rdoc products
rake doc:clobber_plugins              # Remove plugin documentation
rake doc:clobber_rails                # Remove rdoc products
rake doc:plugins                      # Generate documation for all installed plugins
rake doc:rails                        # Build the rails HTML Files
rake doc:reapp                        # Force a rebuild of the RDOC files
rake doc:rerails                      # Force a rebuild of the RDOC files
rake edge                             # freeze rails edge
rake log:clear                        # Truncates all *.log files in log/ to zero bytes
rake rails:freeze:edge                # Lock to latest Edge Rails or a specific revision with REVISION=X (ex: REVISION=4021) or a tag with TAG=Y (ex: TAG=rel_1-1-0)
rake rails:freeze:gems                # Lock this application to the current gems (by unpacking them into vendor/rails)
rake rails:unfreeze                   # Unlock this application from freeze of gems or edge and return to a fluid use of system gems
rake rails:update                     # Update both configs, scripts and public/javascripts from Rails
rake rails:update:configs             # Update config/boot.rb from your current rails install
rake rails:update:javascripts         # Update your javascripts from your current rails install
rake rails:update:scripts             # Add new scripts to the application script/ directory
rake remote_exec                      # Execute a specific action using the release manager
rake rollback                         # Rollback to the release before the current release in production
rake show_deploy_tasks                # Enumerate all available deployment tasks
rake stats                            # Report code statistics (KLOCs, etc) from the application
rake test                             # Test all units and functionals
rake test:functionals                 # Run tests for functionalsdb:test:prepare
rake test:integration                 # Run tests for integrationdb:test:prepare
rake test:plugins                     # Run tests for pluginsenvironment
rake test:recent                      # Run tests for recentdb:test:prepare
rake test:uncommitted                 # Run tests for uncommitteddb:test:prepare
rake test:units                       # Run tests for unitsdb:test:prepare
rake tmp:cache:clear                  # Clears all files and directories in tmp/cache
rake tmp:clear                        # Clear session, cache, and socket files from tmp/
rake tmp:create                       # Creates tmp directories for sessions, cache, and sockets
rake tmp:pids:clear                   # Clears all files in tmp/pids
rake tmp:sessions:clear               # Clears all files in tmp/sessions
rake tmp:sockets:clear                # Clears all files in tmp/sockets
rake update_dialog_helper             # Copies the latest dialog.js to the application's public directory

U can always check the rake tasks list using rake –tasks inside ur rails application.

Categories: rails Tags: , , , , , , ,

Rails Stuff

December 23, 2006 Gaurav Sohoni Leave a comment

Some useful rake commands:

rake migrate version=0
rake test:units
rake test:functionals
rake annotate_models
rake db:sessions:clear
rake doc:app
rake log:clear

rake db:test:prepare -> prepares test database with development database schema

rake -T #displays all rake tasks with description

Generators:

ruby script/generate model ModellName
ruby script/generate controller ListController show edit
ruby script/generate scaffold ModelName ControllerName
ruby script/generate migration AddNewTable
ruby script/generate plugin PluginName
ruby script/generate mailer Notification lost_password signup
ruby script/generate web_service ServiceName api_one api_two
ruby script/generate integration_test TestName
ruby script/generate session_migration

Find:

find(42) # object with ID 42
find([37, 42]) # Array with the objects with id 37, 42
find :all
find :first,
:conditions => [ "name = ?", "Hans" ] # finds the first record with
# the matching condition

more parameters for find:
:o rder => ‘name DESC’ # sql fragment for sorting
:o ffset => 20 # starts with entry 20
:limit => 10 # only return 10 objects
:group => ‘name’ # sql fragment GROUP BY
:joins => ‘LEFT JOIN …’ # additional LEFT JOIN (rarely used)
:include => [:account, :friends] # LEFT OUTER JOIN with these model
:include => { :groups => { :members=> { :favorites } } }
:select => [:name, :adress] # instead of SELECT * FROM
:readonly => true # objects are write protected

Migration:

rake db:migrate
rake db:migrate VERSION=14
rake db:migrate RAILS_ENV=production

Calculations:

Person.average :age
Person.minimum :age
Person.maximum :age
Person.sum :salary, :group => :last_name

Categories: rails Tags: , , , ,