Active Record Demystified

Active Record Demystified

A brief overview of Active Record including some implementation details. Designed to explain some of the "magic" to beginners.

3311968fbb383cc2111af84f36508d93?s=128

Anthony Lewis

March 07, 2012
Tweet

Transcript

  1. Active Record Demystified Anthony Lewis

  2. Any sufficiently advanced technology is indistinguishable from magic. Arthur C.

    Clark
  3. Some people still say that Ruby on Rails has too

    much magic.
  4. It’s not magic.

  5. It’s Ruby

  6. None
  7. Active Record 1. Attributes 2. CRUD 3. Associations

  8. Active Record An object that wraps a row in a

    database table or view, encapsulates the database access, and adds domain logic on that data. Martin Fowler, Patterns of Enterprise Application Architecture
  9. Active Record in Rails • An implementation of the object-relational

    mapping (ORM) pattern of the same name • Automated mapping between classes and tables, attributes and columns • Associations between objects defined by simple class methods
  10. Posts id title body 1 Hello, World Welcome to my

    blog... 2 My Cat The cutest kitty in the... 3 Too Busy Sorry I haven’t posted...
  11. Posts id title body 1 Hello, World Welcome to my

    blog... 2 My Cat The cutest kitty in the... 3 Too Busy Sorry I haven’t posted... a post
  12. Posts id title body 1 Hello, World Welcome to my

    blog... 2 My Cat The cutest kitty in the... 3 Too Busy Sorry I haven’t posted... an attribute
  13. In Code # Not much to see here... class Post

    < ActiveRecord::Base end
  14. At The Console >> Post class Post < ActiveRecord::Base {

    :id => :integer, :title => :string, :body => :text }
  15. But How?

  16. SQL

  17. The Database mysql> SHOW FIELDS FROM `posts`; +--------+--------------+------+-- | Field

    | Type | Null | +--------+--------------+------+-- | id | int(11) | NO | | title | varchar(255) | YES | | body | text | YES | +--------+--------------+------+--
  18. Attributes • Every ActiveRecord object stores the values for its

    attributes in a private variable called @attributes • ActiveRecord also adds methods for accessing each attribute such as title, title=, title?, etc.
  19. Model Attributes p = Post.new p.title = “Hello, World” puts

    p.title # => Hello, World
  20. Attribute Methods def define_method_attribute(attr) module_eval <<-STR def #{attr} read_attribute(#{attr}) end

    STR end
  21. Read Attribute def read_attribute(attr) @attributes.fetch(attr) end

  22. CRUD Create, Read, Update, Delete

  23. Create p = Post.new p.title = “My Cat” p.save #

    or simply Post.create(:title => “My Cat”)
  24. Read p = Post.find(2) p = Post.first p = Post.where(:title

    => “My Cat”) p = Post.order(‘title’).all p = Post.limit(5).all
  25. Update p = Post.find(2) p.title = “2nd” p.save # or

    simply p = Post.find(2) p.update_attributes(:title=>“2nd”)
  26. Delete p = Post.find(2) p.destroy Post.destroy_all

  27. Dynamic Finders # how does this work? p = Post.find_by_title(“My

    Cat”)
  28. Method Missing def method_missing(meth, *args) if meth.to_s =~ /^find_by_(.+)$/ attr

    = $1.split(‘_and_’) find_by_attributes(attr, *args) else super end end
  29. Find By Attributes def find_by_attributes(attr, *args) conditions = Hash[attr.map {

    |a| [a, args[attr.index(a)]] }] where(conditions).first end
  30. Associations Relationships Between Tables

  31. Comments id author body post_id 1 Tom This is the

    worst... 1 2 Fred You are wrong... 1 3 Bob Lowest prices on... 1
  32. Comments id author body post_id 1 Tom This is the

    worst... 1 2 Fred You are wrong... 1 3 Bob Lowest prices on... 1 foreign key
  33. Relationships • Each Post has many Comments • Each Comment

    belongs to a Post
  34. In Code class Post < ActiveRecord::Base has_many :comments end class

    Comment < ActiveRecord::Base belongs_to :post end
  35. Associations • An association is a connection between two models

    • Implemented with macro-style calls that add methods to a model • Streamline the code required to maintain the relationship between models
  36. In Code class Post < ActiveRecord::Base has_many :comments end class

    Comment < ActiveRecord::Base belongs_to :post end
  37. belongs_to Methods • post • post= • build_post • create_post

  38. has_many Methods • comments • comments<< • comments.delete • comments=

    • comments.clear • comments.empty? • comments.size • comments.find • comments.where • comments.exists? • comments.build • comments.create
  39. Without Associations p = Post.find(1) c = Comment.new c.post_id =

    p.id c.author = “Tony” c.body = “A comment” c.save
  40. With Associations p = Post.find(1) p.comments.create( :author => “Tony”, :body

    => “A comment” )
  41. Resources • RailsGuides • http://guides.rubyonrails.org/ • Specifically: • Active Record

    Query Interface • Active Record Associations
  42. Questions?