ActiveRecord ORM usage in Ruby
ActiveRecord ORM is available as the activerecord gem in Ruby. ActiveRecord allows automatic definition of Ruby classes that access the content stored in Database tables.
Given that we have SQL database with the two tables: BlogPost and Comment. We can have two classes representing these tables as well as setting relationships between them with the help from ActiveRecord.
require ‘cookbook_dbconnect’
activerecord_connect
class BlogPost < ActiveRecord::Base
has_name :comments
end
class Comment < ActiveRecord::Base
belongs_to :blog_post
end
Given that you have two classes as defined above, we can start adding records to the database directly with our code via ActiveRecord ORM.
post = BlogPost.create(title: ‘Post Title’, content: ‘Post Content’)
comment = Comment.create(blog_post: post, author: ‘John’, content: “Comment text”)
post.comments.create(author: ‘Ann’, content: ‘This is great’)
Querying for data is also possible with ActiveRecord and it is done with the help of first method.
my_post = BlogPost.first
puts %{“the first post is #{my_post.title}”}
In case we want to iterate over comments for our first blog post, we can employ each method
blog_post.comments.each do |comment|
puts “#{comment.author}”
puts “#{comment.content}”
end
ActiveRecord relies on several techniques available in Ruby. They are conventions, metaprogramming, db introspections. It is important to remember that database names are mapped to ActiveRecord classes. As a result, database names must be defined as lowercase and pluralized nouns with underscores. On the other hand, ActiveRecords should be Camel cased singular names. Please remember these conventions when designing database to be used with ActiveRecord.
ActiveRecords uses decorators in order to set up relationships between database tables
has_many // defines one to many relationship
belongs_to // defines one to many in reverse
has_one //defines one to one relationship
has_and_belongs_to_many // defined many to many relationship
Deletion from the database is accomplished with the use of destroy method.
BlogPost.first.destroy
Deleting BlogPost is easy but ensuring that all the comments are delete is another overhead. On order to ensure this happen, you need to define class BlogPosit with dependencies
class BlogPost < ActiveRecord::Base
has_many :comments, :dependent => destroy
end