====== ActiveRecord ======
sudo gem install activerecord
===== AR Solo =====
ActiveRecord sem rails... SEO purposes =P
**TABELAS SEMPRE NOS PLURAIS**
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => 'mysql', #sqlite,
:database => 'database',
:username => 'user',
:password => 'password',
:host => 'localhost')
=== Mover dados pra outro arquivo: ===
aplicativo.rb
require 'rubygems'
require 'active_record'
require 'yaml'
dbconfig = YAML::load(File.open('database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)
database.yml
adapter: mysql
database: database
username: user
password: password
host: localhost
==== Brincando com AR ====
class Nome_da_tabela_com_letra_maiuscula_plural_ou_nao < ActiveRecord::Base; end
puts Nome_da_tabela_com_letra_maiuscula.find 1
class Tabela < ActiveRecord::Base; end
Tabela.create(:coluna => "valor", :coluna => "valor")
var = Tabela.new
var.coluna = "valor"
var.coluna = :valor
var.save
===== Debug =====
require 'rubygems'
require 'active_record'
require 'yaml'
require 'logger'
dbconfig = YAML::load(File.open('database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)
ActiveRecord::Base.logger = Logger.new(STDERR)
class User < ActiveRecord::Base
end
puts User.count
# SQL (0.000277) SELECT count(*) AS count_all FROM users
# 6
=== Debug p/ arquivo ===
ActiveRecord::Base.logger = Logger.new(File.open('database.log', 'a'))
a => append
w => overwrite
=== Colorização ===
Problemas com log no arquivo? hehe
ActiveRecord.colorize_logging = false
===== Migrations (sem rails) =====
==== Rakefile ====
require 'rake'
require 'active_record'
require 'yaml'
task :default => :migrate
desc "Migrar o banco, recebe ENV[VERSION=x]"
task :migrate => :environment do
ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil )
end
task :environment do
ActiveRecord::Base.establish_connection(YAML::load(File.open('database.yml')))
ActiveRecord::Base.logger = Logger.new(File.open('database.log', 'a'))
end
==== db/migrate ====
Criar esta pasta!
Repare no 001,002,003! **ORDEM!**
=== db/migrate/001_comeco.rb ===
class Comeco < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name, :null => false
t.integer :idade
t.boolean :sexo
t.date :nasc
t.decimal :salario
t.float :bonus
t.text :historia
t.time :agora
t.timestamp
end
end
def self.down
drop_table :users
end
end
=== db/migrate/002_cria_regras.rb ===
Segunda migration
class CriaRegras < ActiveRecord::Migration
def self.up
create_table :roles do |t|
t.string :name, :null => false
t.integer :valor, :null => false
end
end
def self.down
drop_table :roles
end
end
===== Brincando =====
Carregar todas migrations:
rake
Apagar tudo:
rake VERSION=0
rake VERSION=n
====== Source ======
rails.aizatto.com/2007/05/21/activerecord-without-rails/+activerecord+without+rails