Now I would like to show about how to create a simple ActiveRecord example of User.

First thing, we assume that we have one entity called User as below :

We put the file under “activerecord/db/migrate/001_create_user.rb”


class CreateUsers < ActiveRecord::Migration  

def self.up  

 create_table :users do |t|  

t.column :name, :string, :null => false  

end  

end  

 

def self.down  

drop_table :users  

end  

end

And then we create users class that inherit from ActiveRecord::Base that call database connection from database.yml that store information of database connection


require 'rubygems'

require 'active_record'

ActiveRecord::Base.establish_connection(YAML::load(File.open('database.yml')))

class Users < ActiveRecord::Base

end

&#91;/sourcecode&#93;

And here is the database.yml file

&#91;sourcecode lang='xml'&#93;

adapter: sqlite3

  database: development.sqlite3

  pool: 5

  timeout: 5000

&#91;/sourcecode&#93;

After that we create rake file to migate data to database

&#91;sourcecode lang='ruby'&#93;

require 'rubygems'

require 'active_record'

require 'yaml'

require 'rake'      

   task :default => :migrate        

   desc "Migrate the database through scripts in db/migrate. Target specific version with VERSION=x"  

   task :migrate => :environment do  

   ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil )  

   end  

   task :environment do  

   dbconfig = YAML::load(File.open('database.yml')) 

   ActiveRecord::Base.establish_connection(dbconfig)  

   ActiveRecord::Base.logger = Logger.new(File.open('database.log', 'a'))  

  end 

In the end we create one more file called runner.rb to run the example


require 'rubygems'

require 'active_record'

require 'users'

Users.create(:name=>"leakhina")

Advertisements