Раздел «Язык Ruby».RubySchoolSourceL09:
<<Программирование на Ruby

Занятие 9: Введение в ActiveRecord

Следующее занятие
Предыдущее занятие

Установка ПО

$ sudo apt-get install ruby irb rubygems
$ sudo gem install rails sqlite3-ruby

Создание каркаса web-приложения

artem@cde:~/projects$ rails new abc
create  
create  README
create  Rakefile
create  config.ru
create  .gitignore
create  Gemfile
create  app
create  app/helpers/application_helper.rb
create  app/views/layouts/application.html.erb
create  app/controllers/application_controller.rb
create  app/models
create  app/mailers
create  config
create  config/routes.rb
create  config/application.rb
create  config/environment.rb
create  config/environments
create  config/environments/test.rb
create  config/environments/development.rb
create  config/environments/production.rb
create  config/initializers
create  config/initializers/inflections.rb
create  config/initializers/backtrace_silencers.rb
create  config/initializers/session_store.rb
create  config/initializers/secret_token.rb
create  config/initializers/mime_types.rb
create  config/locales
create  config/locales/en.yml
create  config/boot.rb
create  config/database.yml
create  db
create  db/seeds.rb
create  doc
create  doc/README_FOR_APP
create  lib
create  lib/tasks
create  lib/tasks/.gitkeep
create  log
create  log/server.log
create  log/production.log
create  log/development.log
create  log/test.log
create  public
create  public/index.html
create  public/422.html
create  public/404.html
create  public/robots.txt
create  public/favicon.ico
create  public/500.html
create  public/images
create  public/images/rails.png
create  public/stylesheets
create  public/stylesheets/.gitkeep
create  public/javascripts
create  public/javascripts/dragdrop.js
create  public/javascripts/application.js
create  public/javascripts/effects.js
create  public/javascripts/rails.js
create  public/javascripts/prototype.js
create  public/javascripts/controls.js
create  script
create  script/rails
create  test
create  test/performance/browsing_test.rb
create  test/test_helper.rb
create  test/integration
create  test/functional
create  test/unit
create  test/fixtures
create  tmp
create  tmp/sessions
create  tmp/sockets
create  tmp/cache
create  tmp/pids
create  vendor/plugins
create  vendor/plugins/.gitkeep

Создание модели users

artem@cde:~/projects$ cd abc
artem@cde:~/projects/abc$ ./script/rails 
Usage: rails COMMAND [ARGS]

The most common rails commands are:
generate    Generate new code (short-cut alias: "g")
console     Start the Rails console (short-cut alias: "c")
server      Start the Rails server (short-cut alias: "s")
dbconsole   Start a console for the database specified in config/database.yml
(short-cut alias: "db")
new         Create a new Rails application. "rails new my_app" creates a
new application called MyApp in "./my_app"

In addition to those, there are:
application  Generate the Rails application code
destroy      Undo code generated with "generate"
benchmarker  See how fast a piece of code runs
profiler     Get profile information from a piece of code
plugin       Install a plugin
runner       Run a piece of code in the application environment

artem@cde:~/projects/abc$ ./script/rails generate model
Usage:
rails generate model NAME [field:type field:type] [options]

Options:
-o, --orm=NAME  # Orm to be invoked
# Default: active_record

Runtime options:
-p, [--pretend]  # Run but do not make any changes
-s, [--skip]     # Skip files that already exist
-q, [--quiet]    # Supress status output
-f, [--force]    # Overwrite files that already exist

TestUnit options:
[--fixture]                   # Indicates when to generate fixture
# Default: true
-r, [--fixture-replacement=NAME]  # Fixture replacement to be invoked

ActiveRecord options:
[--migration]            # Indicates when to generate migration
# Default: true
[--timestamps]           # Indicates when to generate timestamps
# Default: true
[--parent=PARENT]        # The parent class for the generated model
-t, [--test-framework=NAME]  # Test framework to be invoked
# Default: test_unit

Description:
Create rails files for model generator.

artem@cde:~/projects/abc$ ./script/rails generate model user email:string nickname:string password_hash:string status:int
invoke  active_record
create    db/migrate/20110227091336_create_users.rb
create    app/models/user.rb
invoke    test_unit
create      test/unit/user_test.rb
create      test/fixtures/users.yml

artem@cde:~/projects/abc$ vim db/migrate/20110227091336_create_users.rb

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :email, :limit => 256
      t.string :nickname, :limit => 128
      t.string :password_hash, :limit => 128
      t.integer :status

      t.timestamps
    end
    add_index :users, [:email, :password_hash]
  end

  def self.down
    drop_table :users
  end
end
%ENDCODE

Выполнение миграции


%CODE{bash}%
artem@cde:~/projects/abc$ rake db:migrate
(in /home/artem/projects/abc)
==  CreateUsers: migrating ====================================================
-- create_table(:users)
   -> 0.0009s
-- add_index(:users, [:email, :password_hash])
   -> 0.0003s
==  CreateUsers?: migrated (0.0013s) ===========================================%

Примеры работы в консоли

artem@cde:~/projects/abc$ ./script/rails console
Loading development environment (Rails 3.0.0)
irb(main):001:0> User
=> User(id: integer, email: string, nickname: string, password_hash: string, status: integer, created_at: datetime, updated_at: datetime)
irb(main):002:0> User.count
=> 0
irb(main):003:0> u = User.create(:email=>'a@mail.ru', :nickname => 'aaa')
=> #<User id: 1, email: "a@mail.ru", nickname: "aaa", password_hash: nil, status: nil, created_at: "2011-02-27 09:20:53", updated_at: "2011-02-27 09:20:53">
irb(main):004:0> User.count
=> 1
irb(main):005:0> u.update_attributes(:email => 'b@mail.ru')
=> true
irb(main):006:0> u = User.create(:email=>'h@mail.ru', :nickname => 'hhh')
=> #<User id: 2, email: "h@mail.ru", nickname: "hhh", password_hash: nil, status: nil, created_at: "2011-02-27 09:25:24", updated_at: "2011-02-27 09:25:24">
irb(main):007:0> User.find(:all)
=> [#<User id: 1, email: "b@mail.ru", nickname: "aaa", password_hash: nil, status: nil, created_at: "2011-02-27 09:20:53", updated_at: "2011-02-27 09:24:45">, #<User id: 2, email: "h@mail.ru", nickname: "hhh", password_hash: nil, status: nil, created_at: "2011-02-27 09:25:24", updated_at: "2011-02-27 09:25:24">]
irb(main):008:0> puts User.find(:all).map(&:attributes).to_yaml
--- 
- created_at: 2011-02-27 09:20:53.814991 Z
updated_at: 2011-02-27 09:24:45.311052 Z
nickname: aaa
id: 1
status: 
password_hash: 
email: b@mail.ru
- created_at: 2011-02-27 09:25:24.669452 Z
updated_at: 2011-02-27 09:25:24.669452 Z
nickname: hhh
id: 2
status: 
password_hash: 
email: h@mail.ru
=> nil
irb(main):009:0> User.find(:last, :order=>'created_at')
=> #<User id: 2, email: "h@mail.ru", nickname: "hhh", password_hash: nil, status: nil, created_at: "2011-02-27 09:25:24", updated_at: "2011-02-27 09:25:24">
irb(main):010:0> User.find(:last, :order=>'created_at').created_at
=> Sun, 27 Feb 2011 09:25:24 UTC +00:00
irb(main):011:0> User.find_by_sql('select max(created_at) as created_at from users').inspect
=> "[#<User created_at: \"2011-02-27 09:25:24\">]"
irb(main):012:0> User.find_by_sql('select max(created_at) as created_at from users').first.inspect
=> "#<User created_at: \"2011-02-27 09:25:24\">"
irb(main):013:0> User.find_by_sql('select max(created_at) as created_at from users').first.created_at
=> Sun, 27 Feb 2011 09:25:24 UTC +00:00
irb(main):014:0> User.connection.execute('select max(created_at) as created_at from users').inspect
=> "[{0=>\"2011-02-27 09:25:24.669452\", \"created_at\"=>\"2011-02-27 09:25:24.669452\"}]"
irb(main):015:0> ActiveRecord::Base.connection.execute('select max(created_at) as created_at from users').inspect
=> "[{0=>\"2011-02-27 09:25:24.669452\", \"created_at\"=>\"2011-02-27 09:25:24.669452\"}]"
irb(main):016:0> User.find(:all, :conditions => {:created_at => (Time.now-1.hour..Time.now)})
=> [#<User id: 1, email: "b@mail.ru", nickname: "aaa", password_hash: nil, status: nil, created_at: "2011-02-27 09:20:53", updated_at: "2011-02-27 09:24:45">, #<User id: 2, email: "h@mail.ru", nickname: "hhh", password_hash: nil, status: nil, created_at: "2011-02-27 09:25:24", updated_at: "2011-02-27 09:25:24">]
irb(main):017:0> User.find(:all, :select => 'email', :conditions => {:created_at => (Time.now-1.hour..Time.now)}).map(&:email)
=> ["b@mail.ru", "h@mail.ru"]