1 active records. 2 what’s active records? o-r mapping layer to make database access almost a...

21
1 enkat Subramaniam – [email protected] enkat Subramaniam – [email protected] Active Records

Upload: patience-stevenson

Post on 13-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

1Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Active Records

2Venkat Subramaniam – [email protected] Subramaniam – [email protected]

What’s Active Records?• O-R Mapping layer

• To make database access almost a non-issue• Relies heavily on convention over configuration

– some say this is simple, others say this is simplistic– Tables map to classes– Rows map to objects– Columns map to attributes

• You write minimal code– Quite a bit of code is synthesized behind the scene

3Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Accessing Data• You derive your class from

ActiveRecord::Base• That’s almost all you need• You are provided with methods you can

readily use• Attributes are inferred based on column

names in schema– You may have additional attributes

• Like having a clear text password in memory while the password column is encrypted

• Has primary key id by convention

4Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Locking• Supports Pessimistic or Optimistic

Locking

• Optimistic if your table has an integer column named lock_version– Active Records take care of rest

• You can control this by ActiveRecord::Base.lock_optimistically = false

5Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Classes to Tables• Active Record assumes the table name is

plural form of your model class– Multiword class name transorms to words

separated by underscores– Controlled by global glag in environment.rb

• ActiveRecord::Base.pluralize_table_names = false

– Common plurans and then some weird ones• people (Person), journals (Journal), children

(Child), dear_friends (DearFriend)

• You can break away from the convention (for legacy database) using set_table directive

6Venkat Subramaniam – [email protected] Subramaniam – [email protected]

MySql• Create mysql database

– mysql– create database csalum_development;

• Create a create.sql script for creating table

• Run script– mysql –p –r root csalum_development < create.sql

7Venkat Subramaniam – [email protected] Subramaniam – [email protected]

A Model Class

8Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Exploring Active Records• Columns() method tells us

9Venkat Subramaniam – [email protected] Subramaniam – [email protected]

SQL Type to Ruby Type Mapping• Standard SQL to Ruby type mapping• int, integer -> Fixnum• decimal, numeric, float, double -> Float• interval, date -> Date• clob, blob, text, char, varchar, string -> String• datetime, time -> Time• Money? – decimal to float may lead to rounding

errors– For currency you may use

• units of cents• aggregate Money objects

10Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Accessing Attributes• Active Records converts column values to

appropriate Ruby types• You can get raw value of an attribute as well by

appending attribute name with _before_type_cast

• Use caution with boolean types– No consistent represenation in databases– Use the ? form of method to get correct value– Still poses problems for i18n

11Venkat Subramaniam – [email protected] Subramaniam – [email protected]

CRUD• Active Records is based on the simple

notion that you mostly need basic operations on tables– Create, Read, Update, and Delete

• Methods for these are synthesized behind the scene– new– finders– save– update– Delete

12Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Creating A Row• Use new to create object• Remember to save

13Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Ways to create

14Venkat Subramaniam – [email protected] Subramaniam – [email protected]

create() Method• Combines new and save method• create(hash) => object• create(array_of_hash) => objects

15Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Reading• find takes primary key or an array of

primary keys• Gets fancier than that as well

– Can take other parameters

• :first specified to return first matching row

• :all specified to return all matching rows• :condition helps send parameters to SQL

where clause

16Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Reading

No guarantee on ordering unless you specify order by

17Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Specifying Criteria• Unsafe way – SQL Injection problem

– Don’t try this at home

18Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Specifying Criteria – Better Ways

19Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Specialized finds• You can search based on column values• Methods synthesized for you

20Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Update/Save• Save updates existing row or inserts a new row• save returns true if model is valid and can be

saved• save! raises a RecordInvalid exception if objects

can’t be saved• You may also use update_attribute or

update_attributes• Class method update allows you to update a

row without reading it• update_all is like SQL update with SET and

WHERE clause

21Venkat Subramaniam – [email protected] Subramaniam – [email protected]

Deleting• destroy allows you to delete a row based

on id or condition

• Once deleted, object in memory is frozen

• destroy_all is a classes methods that destroys all objects that meet given condition