Rails 3 ActiveRecord
-
Upload
blazing-cloud -
Category
Technology
-
view
1.616 -
download
0
description
Transcript of Rails 3 ActiveRecord
ActiveRecord::Base
Cur$s Schofield
$ rails new ar_ex
$ rails -v
3.0.3
Edit Gemfile
source 'http://rubygems.org' gem ‘rails’,‘3.0.3’ gem ‘rspec-rails’ gem ‘sqlite3-ruby’, :require => ‘sqlite’
$ bundle
$ rails g rspec:install
$ rails g model Message body:text public_key:text
invoke rspec
create spec/models/message_spec.rb
require 'spec_helper'
describe Message do pending "a class in itself"end
invoke active_record
create db/migrate/20110208201036_create_messages.rb
class CreateMessages < ActiveRecord::Migration def self.up # rake db:migrate end def self.down # rake db:migrate:down VERSION=file_name # rake db:migrate:redo VERSION=file_name endend
create_table :messages do |t| t.text :body t.text :public_key
t.timestamps end
rails g model Message body:text public_key:text
drop_table :messages
http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements
create app/models/message.rb
class Message < ActiveRecord::Baseend
Where are the methods?
$ rails console
> Message.new
ActiveRecord::StatementInvalid:
Could not find table 'messages'
from /Users/o_o/.rvm/gems/ruby-1.9.2-p0@rails3/gems/activerecord-3.0.3/lib/active_record/connection_adapters/sqlite_adapter.rb:295:in `table_structure'
every model has a corresponding database table
$ rails db
PRAGMA table_info(messages);
nothing!
.quit;
$ rake db:migrate
$ rails db
PRAGMA table_info(messages);
0|id|INTEGER|1||11|body|text|0||02|public_key|text|0||03|created_at|datetime|0||04|updated_at|datetime|0||0
.quit
$ rails console
> Message.new
=> #<Message id: nil, body: nil, public_key: nil, created_at: nil, updated_at: nil>
>msg = Message.new>msg.body = 2>msg.save>msg
=> #<Message id: 1, body: 2, public_key: nil, created_at: "2011-02-08 20:56:33", updated_at: "2011-02-08 20:56:33">
> msg.body.class
=> Fixnum
> Message.find(1)
=> #<Message id: 1, body: "2", public_key: nil, created_at: "2011-02-08 20:56:33", updated_at: "2011-02-08 20:56:33">
> Message.find(1).body.class
=> String
> Message.find(1).updated_at.class
=> ActiveSupport::TimeWithZone
With Great Power Comes With Great Responsibility
One more time..
$ rails console
> ActiveRecord::Base.logger=Logger.new($stdout)
> Message.new.save
SQL (0.3ms) SELECT name FROM sqlite_master WHERE type = 'table' AND NOT name = 'sqlite_sequence'
AREL (0.5ms) INSERT INTO "messages" ("body", "public_key", "created_at", "updated_at") VALUES (NULL, NULL, '2011-02-09 01:55:09.111181', '2011-02-09 01:55:09.111181')
> exit
Active Record Features
validationshttp://apidock.com/rails/v3.0.0/ActiveModel/Validations
before_save
http://apidock.com/rails/v3.0.0/ActiveRecord/Callbacks
scopeshttp://apidock.com/rails/v3.0.0/ActiveRecord/NamedScope/
ClassMethods/scope
Understanding is free with practice - Without practice understanding cannot stand.