Active Scaffold for Rails: Many to Many

Yesterday I downloaded Active Scaffold and played around with it. I have to say its pretty nice and really easy to use.

  1. script/plugin install http://activescaffold.googlecode.com/svn/tags/active_scaffold
  2. create three tables items, baskets, and baskets_items (see SQL below)
  3. create a simple layout with two includes

    < %= javascript_include_tag :defaults %>
    < %= active_scaffold_includes %>
  4. create two models examples below SQL, Item and Basket and add has_and_belongs_to_many :items to Basket
  5. create two controllers one for Item and one for Basket and make sure each has the keyword active_scaffold
  6. navigate to items or baskets and enjoy!
SQL for tables


DROP TABLE IF EXISTS baskets;

CREATE TABLE baskets (
id INT(11) NOT NULL AUTO_INCREMENT,
basket_name VARCHAR(40) NOT NULL COMMENT 'name of the basket, should match event',
PRIMARY KEY (id)
)
ENGINE=INNODB;

DROP TABLE IF EXISTS items;

CREATE TABLE items (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(40) NOT NULL COMMENT 'name of the item',
qualities VARCHAR(40) NOT NULL COMMENT 'comma seperated list of qualities we may infer about the person consuming the item',
PRIMARY KEY (id)
)
ENGINE=INNODB;

DROP TABLE IF EXISTS baskets_items;

CREATE TABLE baskets_items (
basket_id INT(11) NOT NULL,
item_id INT(11) NOT NULL,
PRIMARY KEY (basket_id,item_id)
)
ENGINE=INNODB;

Many-to-Many models


class Basket < ActiveRecord::Base
has_and_belongs_to_many :items
end

class Item < ActiveRecord::Base
end

Controllers


class BasketsController < ApplicationController

layout "active_scaffold"
active_scaffold :basket

end

class ItemsController < ApplicationController

layout "active_scaffold"
active_scaffold :items

end

Leave a Reply