More Related Content Similar to ActiveRecord (20) More from Blazing Cloud (20) ActiveRecord7. RUBY-DRIVEN SCHEMA
• scaffold generates
db/migrate/20110131021702_create_people.rb
• rake db:migrate
runs the migration, creates the table
• Watch what we did before in slow motion...
10. RAILS CONSOLE
>> ActiveRecord::Base.logger = Logger.new(STDOUT)
>> Person.first
SQL (1.0ms) SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
Person Load (1.0ms) SELECT "people".* FROM "people" LIMIT 1
=> #<Person id: 2, first_name: "Wilma", last_name: "Flinstone",
created_at: "2010-10-19 19:59:36", updated_at: "2010-10-19
19:59:36">
11. RAILS CONSOLE
>> ActiveRecord::Base.logger = Logger.new(STDOUT)
>> Person.first
SQL (1.0ms) SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
Person Load (1.0ms) SELECT "people".* FROM "people" LIMIT 1
=> #<Person id: 2, first_name: "Wilma", last_name: "Flinstone",
created_at: "2010-10-19 19:59:36", updated_at: "2010-10-19
19:59:36">
find "people" table name
12. RAILS CONSOLE
>> ActiveRecord::Base.logger = Logger.new(STDOUT)
>> Person.first
SQL (1.0ms) SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
Person Load (1.0ms) SELECT "people".* FROM "people" LIMIT 1
=> #<Person id: 2, first_name: "Wilma", last_name: "Flinstone",
created_at: "2010-10-19 19:59:36", updated_at: "2010-10-19
19:59:36">
find first row in "people table"
13. DYNAMIC GETTERS AND
SETTERS
>> bret = Person.new
>> bret.first_name = "Bret"
>> bret.last_name = "Smith"
>> bret.first_name
"Bret"
>> bret.xxx
NoMethodError
14. MORE ACTIVE RECORD
• save to database as needed
• automatically handle update/insert
• dynamic queries
16. SAFE FROM SQL INJECTION
class User < ActiveRecord::Base
def self.authenticate_unsafely(user_name, password)
find(:first, :conditions =>
"user_name = '#{user_name}' AND password = '#{password}'")
end
def self.authenticate_safely(user_name, password)
find(:first, :conditions =>
[ "user_name = ? AND password = ?", user_name, password ])
end
def self.authenticate_safely_simply(user_name, password)
find(:first, :conditions =>
{ :user_name => user_name, :password => password })
end
Editor's Notes \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n