📜 ⬆️ ⬇️

ActiveRecord Philosophy

Today in our article we will look at a pattern called ActiveRecord, which is a tool for working with a database. Immediately I will ask professionals not to criticize such kind of notes. They are written only in order to encourage, give an incentive to read such books as Agile Web Development with Ruby on Rails.

It would be more correct to even call ActiveRecord an implementation of the ORM technology:
“ORM (Object-relational mapping) is a programming technology that links databases with the concepts of object-oriented programming languages, creating a“ virtual object database ”

ActiveRecord in Ruby on Rails pleased me a lot when I first met him. Its implementations can be found in various web frameworks like RoR, CakePHP, Castle and so on. The idea is that each database table turns into a class , each row of the table into an object of this class. ActiveRecord provides methods for working with data in each column of a table.

Let's say, let us have a table with the data of the Habra-population of users , then add a record about the new comrade who wants to replenish these slender ranks can be this way:
x = User.new
x.name = " "
x.login = "ivanov"
x.email = "no@reply.com"
x.homepage = "ivanov-thebest.com -- "
x.save

These magic operations will create and send the following query to the database:
')
INSERT INTO users (name, login, email, homepage) VALUES
\ (' ', 'ivanov', 'no@reply.com', 'ivanov-thebest.com -- ');


With no less success, you can search and select records from the database in the following way:
#
f = User.find(:all)
# ivanov
search_str = "ivanov"
f = User.find(:first, :conditions => ["login = ?", search_str])

Such a technique will automatically protect us from SQL injection (this will be done by Rails for us in the variant above), and will also generate the following query:

SELECT * FROM users WHERE login = 'ivanov'

Thanks to Rails and their caring developers, the above can be made even easier:

f = User.find_by_login("ivanov")

Here, in the briefest summary, everything is set up :) And whoever is interested, I advise you to start with the page of RelsoViki dedicated to ActiveRecord , and then (if you just want to go to the hell), open Active Record Reference Documentation . Lazy I propose to continue to read this blog, something else must tell, the benefit of ActiveRecord stories no end. Brave - do not wait for the continuation, and try-try-try.

Source: https://habr.com/ru/post/11525/


All Articles