active_record

Generating association while generating model

May be you guys are already aware of, but in Rails 2.2 we can specify belongs_to association while generating model. So if we issue:

script/generate model Post title:string author:belongs_to

We will get a Post model like:

class Post < ActiveRecord::Base
  belongs_to :author
end

Also it will automatically add the foreign key column in the migration.

class CreatePosts < ActiveRecord::Migration
  def self.up
    create_table :posts do |t|
      t.string :title
      t.belongs_to :author

      t.timestamps
    end
  end

  def self.down
    drop_table :posts
  end
end

Nothing much but saves some keystrokes. :-)

ActiveRecord finder: Now we can use hash as conditions

Earlier conditions can either be specified as a string or array now in edge rails we can specify hash also. So if we specify conditions as hash then it will generate conditions based on equality with SQL AND.

Example:

User.find(:all, :conditions=>{:first_name => ‘akhil’, :role => ‘admin’})

will generate SQL as “where `first_name` = ‘akhil’ and `role` = ‘admin’”

Also we can have range as condition

Example:

User.find(:all, :conditions => {:access_level => 3..5})

will generate SQL as “where `access_level` BETWEEN 3 AND 5″

This is really helpful modification in ActiveRecord :-)