Plugins - Acts As Unimaginative Join Model

StarAdd to favorites

A simple shortcut to ease the promotion of simple HABTM relations to join models.

For example, if you had have two models called Person and Phone, which are joined by a has and belongs to many relationship. The join table would be named people_phones, and the models would be like so:

  class Person < ActiveRecord::Base
    has_and_belongs_to_many :phones
  end

  class Phone < ActiveRecord::Base
    has_and_belongs_to_many :people
  end

At a later date you decide there needs to be some extra data stored in the join, such as the extension number for the person, as many people could have the same phone number but with different extension. So you create a new model called PersonPhone to act as the join model, and add the new extension column to the people_phones table.

The models will then need to be changed like so:

  class Person < ActiveRecord::Base
    has_many :person_phones
    has_many :phones, :through => :person_phones
  end

  class PersonPhone < ActiveRecord::Base
    acts_as_unimaginative_join_model
  end

  class Phone < ActiveRecord::Base
    has_many :person_phones
    has_many :people, :through => :person_phones
  end

The only bit of magic here is acts_as_unimaginative_join_model which looks at the model name and calls set_table_name, as well as setting the correct belongs_to associations. In this case it’s equivalent to writing:

  class PersonPhone < ActiveRecord::Base
    set_table_name 'people_phones'
    belongs_to :person
    belongs_to :phone
  end

Only two lines saved… but with a dozen join models it pay offs.

Tags

Comments

Add a comment

Search Plugins

Query syntax

Plugins by Category

Sponsors

Rails Kits: Get Code. Get Moving.

Have a comment?