Wednesday, March 10, 2010

HABTM Custom Join Table in RoR

has_and_belongs_to_many(association_id, options = {}, &extension) public
Specifies a many-to-many relationship with another class. This associates two classes via an intermediate join table. Unless the join table is explicitly specified as an option, it is guessed using the lexical order of the class names. So a join between Developer and Project will give the default join table name of "developers_projects" because "D" outranks "P". Note that this precedence is calculated using the < operator for String. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the custom :join_table option if you need to.

The join table should not have a primary key or a model associated with it. You must manually generate the join table with a migration such as this:

class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
def self.up
create_table :developers_projects, :id => false do |t|
t.integer :developer_id
t.integer :project_id
end
end

def self.down
drop_table :developers_projects
end
end

Custom Join Table Example

For Products and Categories default join table in lexical order is
categories_products.

if we want to use custom join table (prod_cats) than use 'join_table' option

class Products < ActiveRecord::Base
has_and_belongs_to_many :categories, :join_table => :prod_cats
end

class Categories < ActiveRecord::Base
has_and_belongs_to_many :products, :join_table => :prod_cats
end

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.