Thursday, July 28, 2011

#change

Do you now about change?
In Rails 3.1 ActiveRecord::Migration we can define only one method
change
It`s 'reversible' migrations. You just implement 'up' version and Migration system generate for you methods to create revers migration.
For example:
class CreateWagons < ActiveRecord::Migration
  def change
    create_table :wagons do |t|
      t.integer :number
      t.integer :mileage
      t.datetime :build_date
    end
  end
end
When you run migration 'up' it create a new table, if 'down' - drop dable. But you must be careful using this magick, because some methods can`t be resolved and you get ActiveRecord::IrreversibleMigration
Rails known how to revert this commands:
add_column
add_index
add_timestamp
create_table
remove_timestamps
rename_column
rename_index
rename_table
There for you can create 'change' migration. Try to run it 'up' and 'down', and if you migration raised, you just implement 'down' version.
I think it`s one more beautiful issues that presents to us Rails platform.

Friday, April 29, 2011

sticker

This sticker i must put on my display :) command to create TAGS file

$ cd rails_root_path
$ ctags -e -a --Ruby-kinds=-f -o TAGS -R .

Friday, April 22, 2011

Inside rails.

You must be very careful when create "before_*" callbacks in Rails.

I found one interesting feature (of course it is not bug :D ) ActiveRecord raise with error RecordNotSaved if you have "before_*" callback that return "false". For example:

class User < ActiveRecord::Base
  before_save :set_short_link

  private
  def set_short_link
    short_link = name.to_url if name.changed?
  end
end

You can`t save instance of this class if you don`t change "name" because method "set_short_link" return false (see /activerecord/lib/active_record/base.rb, line 2568)

Right version will be:

class User < ActiveRecord::Base
  before_save :set_short_link

  private
  def set_short_link
    short_link = name.to_url if name.changed?
    true
  end
end