1 / 21

Active Records

Active Records. 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

dbowman
Download Presentation

Active Records

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Active Records

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

  7. A Model Class

  8. Exploring Active Records • Columns() method tells us

  9. 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

  10. 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

  11. 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

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

  13. Ways to create

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

  15. 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

  16. Reading No guarantee on ordering unless you specify order by

  17. Specifying Criteria • Unsafe way – SQL Injection problem • Don’t try this at home

  18. Specifying Criteria – Better Ways

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

  20. 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

  21. 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

More Related