Avoiding Polymorphic Associations in Rails -


(sorry bad english)

let's suppose have models a, b, c. each model have 1 address.

in book "sql antipatterns: avoiding pitfalls of database programming" (chapter 7 - polymorphic associations) there recipe avoid such associations through use of "common super table" (also called base table or ancestor table).

polymorphically, be:

table addresses:     id: integer     parent_type:string  # 'a', 'b' or 'c'     parent_id: integer 

i know can use intersection tables, following solution looks more polished:

instead of polymorphically associating a, b, c address, recipe suggests create super table (addressing) have id field (surrogate key or pseudo key). then, other tables references addressing. way, says author, "you can rely on enforcement of database’s data integrity foreign keys". so, be:

table addressing     id: integer table addresses     id: integer     addressing_id: integer  (foreign_key)     zip: string table     id: integer     addressing_id: integer  (foreign_key)     name: string table b     id: integer     addressing_id: integer  (foreign_key)     name: string table c     id: integer     addressing_id: integer  (foreign_key)     name: string 

the sql query this:

select *   join address using addressing_id   a.addressing_id = 1243  

the question is: how code such scenario in rails ? i've tried in several ways without success.

do objects a, b , c each have single address? or many addresses? comment below looks each object has 1 address.

if every object has 1 address can put foreign key in a/b/c objects address id. let house or office objects have 1 address:

class house < activerecord::base   belongs_to :address end  class office < activerecord::base   belongs_to :address end 

your offices , houses db tables need have foreign key address_id. way can access object's address house.address or office.address.

if these objects have many addresses, solution depends on a/b/c objects. if related use single table inheritance - rails supports pattern well - without more information it's difficult best approach.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -