开发者

What is Ruby on Rails ORM in layman's terms? Please explain

开发者 https://www.devze.com 2022-12-14 18:54 出处:网络
I am having trouble understanding ORM in Ruby on Rails. From what I understand there is a 1:1 relationship between tables/columns and objects/attributes. So every record is an object.

I am having trouble understanding ORM in Ruby on Rails. From what I understand there is a 1:1 relationship between tables/columns and objects/attributes. So every record is an object. Also what exactly is a Model? 开发者_如何学编程I know it maps to a table.

What I'm really after is a deeper understanding of the above. Thank you in advance for your help

I'm a Web developer going from PHP to Ruby on Rails.


"From what I understand there is a 1:1 relationship between tables/columns and objects/attributes. So every record is an object."

That is not exactly correct, unless you use the term "object" very loosely. Tables are modelled by classes, while table records are modeled by instances of those classes.

Let's say you have a clients table, with columns id (autonum) and name (varchar). Let's say that it has only one record, id=1 and a name="Ford". Then:

  • The DB table clients will map to the model class Client.
  • The record will map to a model instance, meaning that you have to create the object and assign it to a variable in order to work with the record. The most common way would be to do ford = Client.find(1)
  • The two columns of the table will map to methods on the ford variable. You can do ford.id and you will get 1. You can do ford.name and you will get the string "Ford". You can also change the name of the client by doing ford.name = "Chevrolet", and then commit the changes on the database by doing ford.save.

"Also what exactly is a Model? I know it maps to a table"

Models are just classes with lots of very useful methods for manipulating your database. Here are some examples:

  • Validations: Besides the typical db-driven validations ("this field can't be null") you can implement much complex validations in ruby ("this field must be a valid email" is the most typical one). Validations are run just before you invoke "save" on a model instance.
  • Relationships: The foreign keys can also be mapped onto models. For example, if you had a brands table (with its corresponding Brand model) associated via a foreign key to your ford client, you could do ford.brands and you would get an array of objects representing all the records on the brands table that have a client_id = 1.
  • Queries: Models allow you to create queries in ruby, and translate them to SQL themselves. Most people like this feature.

These are just some examples. Active record provides much more functionalities such as translations, scoping in queries, or support for single table inheritance.

Last but not least, you can add your own methods to these classes.

Models are a great way of not writing "spaguetti code", since you are kind of forced to separate your code by functionality.

  • Models handle database interaction, and business logic
  • Views handle html rendering and user interaction
  • Controllers connect Models with Views


ORM in Rails is an implementation of the Active Record pattern from Martin Fowler's Patterns of Enterprise Application Architecture book. Accordingly, the Rails ORM framework is named ActiveRecord.

The basic idea is that a database table is wrapped into a class and an instance of an object corresponds to a single row in that table. So creating a new instance adds a row to the table, updating the object updates the row etc. The wrapper class implements properties for each column in the table. In Rails' ActiveRecord, these properties are made available automatically using Ruby metaprogramming based on the database schema. You can override these properties if required if you need to introduce additional logic. You can also add so-called virtual attributes, which have no corresponding column in the underlying database table.

Rails is a Model-View-Controller (MVC) framework, so a Rails model is the M in MVC. As well as being the ActiveRecord wrapper class described above it contains business logic, including validation logic implemented by ActiveRecord's Validation module.

Further Reading

  • Rails Database Migrations guide
  • Rails Active Record Validations and Callbacks guide
  • Active Record Associations guide
  • Active Record Query Interface guide
  • Active Record API documentation


Models: Domain objects such like User, Account or Status. Models are not necessarily supported by a database backend, as for example Status can be just a simple statically-typed enumeration.

ActiveRecord:

Provides dynamic methods for quering database tables. A database table is defined as a class which inherits ActiveRecord class (pseudo-PHP example):

class User extends ActiveRecord {}

//find a record by name, and returns an instance of `User`
$record = User::find_by_name("Imran");
echo $record->name; //prints "Imran"

//there are a lot more dynamic methods for quering

New records are created by creating new instances of ActiveRecord-inherited classes:

class Account extends ActiveRecord {}

$account = new Account();
$account->name = "Bank Account"; 
$account->save();


There are two pieces here: the ORM and Rails's MVC pattern. ORM is short for "object-relational mapping", and it does pretty much what it says: it maps tables in your database to objects you can work with.

MVC is short for "model-view-controller", the pattern that describes how Rails turns your domain behavior and object representations into useful pages. The MVC pattern breaks down into three chunks:

  • Models contain a definition of what an object in your domain represents, and how it is related to other models. It also describes how fields and relationships represented in the object map to backing stores (such as a database). Note that, per se, there's nothing about a model which prescribes that you have to use a particular ORM (or even an ORM at all).

  • Controllers specify how models should interact with each other to produce useful results in response to a user request.

  • Views take the results created by controllers and render them in the desired way. (By the time you get to your view, you should mostly know what's being rendered, and there should be very little behavior happening.)


The definition from Wikipedia:

Object-relational mapping (ORM, O/RM, and O/R mapping) in computer software is a programming technique for converting data between incompatible type systems in relational databases and object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language.

From a PHP view it will be in the following way(via example)

  1. Connect to the database and get some row from posts table.
  2. Turn that row to an object with attributes like those in the table columns.
  3. If the posts has comments in comments table, you can also do post.comments and you get the comments also as an array of objects as well.

You can define relationships between tables like saying: Posts has_many Comments, a Comment belongs to a post and so.

So basically you are not working with database rows, instead you turn those rows and their relationships to objects with composition or inheritance relationships.


In layman's terms.

  • A Rails Model is proxy to a table in the database. These models happens to be Ruby classes.
  • The objects of these classes are proxies to rows in the table of which this model is a proxy.
  • Finally the attributes of these objects are proxies to the column data for that particular row.

Above is actually the Rails ActiveRecord ORM.


1:1 is not quite correct, since there is object-relation impedance mismatch.

0

精彩评论

暂无评论...
验证码 换一张
取 消