single table inheritance

7
Single Table Inheritance Herencia de tablas con Rails :) por Nelson Rojas Núñez nelsonrojas.wordpress.com

Upload: nelson-rojas-nunez

Post on 03-Aug-2015

649 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Single table inheritance

Single Table Inheritance

Herencia de tablas con Rails :)por Nelson Rojas Núñez

nelsonrojas.wordpress.com

Page 2: Single table inheritance

El problemaAds-name-body-published

Posts-name-body-published

Pages-name-body-published

Las tres tablas apuntan a elementos diferentes, tienen los mismos campos, pero usan 3 tablas en la base de datos.

class Ad < ActiveRecord::Base

class Post < ActiveRecord::Base

class Page < ActiveRecord::Base

Page 3: Single table inheritance

Usando Single Table Inheritance

Entries-name-body-published-type

class Entry < ActiveRecord::Base

Ad Post Page

class Ad < Entry class Post < Entry class Page < Entry

Page 4: Single table inheritance

Ejemplo$ rails demo

demo$ ruby script/generate model entry name:string body:text published:boolean type:stringdemo$ rake db:migrate demo$ ruby script/generate model post --skip-migrationdemo$ ruby script/generate model ad --skip-migration demo$ ruby script/generate model page --skip-migration

Las Clasesclass Entry < ActiveRecord::Baseend class Page < Entryend

class Post < Entryend

class Ad < Entryend

Page 5: Single table inheritance

Usemos la consola para probar>> o = Post.new>> #<Post id: nil, name: nil, body: nil, published: nil, type: "Post", created_at: nil, updated_at: nil>>> o.name = "mi primer post">> o.body = "este es el cuerpo de mi primer post">> o.published = true>> o.save

>> p = Page.new>> #<Page id: nil, name: nil, body: nil, published: nil, type: "Page", created_at: nil, updated_at: nil>>> p.name = "mi primera pagina">> p.body = "este es el cuerpo de mi primera pagina">> p.published = true>> p.save

>> Entry.count=> 2

>> Post.count=> 1

>> Page.count=> 1

Page 6: Single table inheritance

Conclusiones

Lo bueno ● Permite realizar búsquedas en un único lugar para cosas

diferentes.● Menos código para mantención.● Herencia elegante :)

Lo malo

● No es la panacea, por tanto no abusar de ella cuando los elementos requieren tratamientos diferentes. Una mala idea es hacer herencia con órdenes de compra, facturas y guías.