Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Active Record inheritance in Ruby on Rails?

How to implement inheritance with active records?

For example, I want a class Animal, class Dog, and class Cat.

How would the model and the database table mapping be?

like image 761
andrisetiawan Avatar asked Oct 21 '09 05:10

andrisetiawan


People also ask

What is Active Record in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

How does inheritance work in Rails?

Two methods that Rails gives us to deal with this event are single-table inheritance and polymorphic association. In Single-Table Inheritance (STI), many subclasses inherit from one superclass with all the data in the same table in the database.

What is inheritance in Ruby on Rails?

Inheritance is when a class receives or inherits the attributes and behavior of another class. The class that is inheriting the behavior is called the subclass (or derived class) and the class it inherits from is called the superclass (or base class). Imagine several classes - Cat, Dog, Rabbit, and so on.

What is STI in Ruby?

Single-table inheritance (STI) is the practice of storing multiple types of values in the same table, where each record includes a field indicating its type, and the table includes a column for every field of all the types it stores.


1 Answers

Rails supports Single Table Inheritance.

From the AR docs:

Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed by overwriting Base.inheritance_column). This means that an inheritance looking like this:

class Company < ActiveRecord::Base; end    class Firm < Company; end   class Client < Company; end    class PriorityClient < Client; end 

When you do Firm.create(:name => "37signals"), this record will be saved in the companies table with type = "Firm". You can then fetch this row again using Company.find(:first, "name = ‘37signals’") and it will return a Firm object.

If you don‘t have a type column defined in your table, single-table inheritance won‘t be triggered. In that case, it‘ll work just like normal subclasses with no special magic for differentiating between them or reloading the right type with find.

A pretty good tutorial is here: http://juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/

like image 125
Toby Hede Avatar answered Oct 04 '22 14:10

Toby Hede