Skip to content

Instantly share code, notes, and snippets.

@ognevsky
Created July 3, 2011 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ognevsky/1062185 to your computer and use it in GitHub Desktop.
Save ognevsky/1062185 to your computer and use it in GitHub Desktop.
ActiveRecord example
⇥ rails generate model user
invoke active_record
create db/migrate/20110703115918_create_users.rb
create app/models/user.rb
invoke test_unit
create test/unit/user_test.rb
create test/fixtures/users.yml
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.timestamps
end
end
def self.down
drop_table :users
end
end
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :login, :null => false
t.string :password, :null => false
t.boolean :active, :default => false
t.timestamps
end
end
def self.down
drop_table :users
end
end
== CreateUsers: migrating ====================================================
-- create_table(:users)
-> 0.0107s
== CreateUsers: migrated (0.0109s) ===========================================
>> User.new
=> #<User id: nil, login: nil, password: nil, active: false, created_at: nil, updated_at: nil>
>> user = User.new(:login => "Vasya", :password => "password")
=> #<User id: nil, login: "Vasya", password: "password", active: false, created_at: nil, updated_at: nil>
>> user.new_record?
=> true
>> user.login_changed?
=> true
>> user.save
SQL (0.4ms) SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
AREL (0.4ms) INSERT INTO "users" ("login", "password", "active", "created_at", "updated_at") VALUES ('Vasya', 'password', 'f', '2011-07-03 12:16:40.408914', '2011-07-03 12:16:40.408914')
=> true
>>
>> User.find_by_login("Vasya")
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."login" = 'Vasya' LIMIT 1
=> #<User id: 1, login: "Vasya", password: "password", active: false, created_at: "2011-07-03 12:16:40", updated_at: "2011-07-03 12:16:40">
>> User.all
User Load (0.4ms) SELECT "users".* FROM "users"
=> [#<User id: 1, login: "Vasya", password: "password", active: false, created_at: "2011-07-03 12:16:40", updated_at: "2011-07-03 12:16:40">]
>> User.first
User Load (0.4ms) SELECT "users".* FROM "users" LIMIT 1
=> #<User id: 1, login: "Vasya", password: "password", active: false, created_at: "2011-07-03 12:16:40", updated_at: "2011-07-03 12:16:40">
>> User.find_by_login_and_password("Vasya", "password")
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."login" = 'Vasya' AND "users"."password" = 'password' LIMIT 1
=> #<User id: 1, login: "Vasya", password: "password", active: false, created_at: "2011-07-03 12:16:40", updated_at: "2011-07-03 12:16:40">
>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment