activerecord Getting started with activerecord

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Remarks

Active record is an architectural pattern of modeling database objects. In this pattern classes match very closely the structure of underlying database.

Pseudocode

The pattern can be illustrated by the following pseudocode:

product = new Product()
product.name = "Some Book"
product.price = 123.45
product.save()
 

The following SQL would be a result:

INSERT INTO products (name, price) VALUES ('Some Book', 123.45);
 

Java

In Java, activerecord pattern isn't very popular. Though there are some implementations:

Ruby on Rails

ActiveRecord pattern was popularized by Rails. It's the default ORM there.

Conventions

Rails ActiveRecord is driven by conventions: class names are mapped to table names, field names are mapped to field names, foreign and primary keys should be named accordingly. These conventions can be overridden.

Query

Having the following schema:

CREATE TABLE products (
   id int(11) NOT NULL auto_increment,
   name varchar(255),
   PRIMARY KEY  (id)
);
 

And the following code:

class Product < ApplicationRecord
end
p = Product.new
p.name = "Some Book"
p.save!
 

Will produce the following statement:

INSERT INTO products (name) VALUES ("Some Book");
 


Got any activerecord Question?