Skip to content

Instantly share code, notes, and snippets.

@danchoi
Created February 28, 2013 14:17
Show Gist options
  • Select an option

  • Save danchoi/5057048 to your computer and use it in GitHub Desktop.

Select an option

Save danchoi/5057048 to your computer and use it in GitHub Desktop.
require 'active_record'
class Grouping < ActiveRecord::Base
has_and_belongs_to_many :values
has_and_belongs_to_many :characteristics
end
class Characteristic < ActiveRecord::Base
has_and_belongs_to_many :groupings
has_many :values, :through => :groupings
end
class Value < ActiveRecord::Base
has_and_belongs_to_many :groupings
has_many :characteristics, :through => :groupings
end
ActiveRecord::Base.establish_connection(
database: "ari",
adapter: "postgresql"
)
Grouping.delete_all
Characteristic.delete_all
Value.delete_all
g1 = Grouping.create name: "group g1"
v1 = Value.create name: "value v1"
c1 = Characteristic.create name: "characteristic c1"
c2 = Characteristic.create name: "characteristic c2"
g1.characteristics << c1 << c2
g1.values << v1
puts "g1: ", g1.inspect
puts "g1 characteristics: ", g1.characteristics.map(&:name).inspect
puts "c1 values: ", c1.values.map(&:name).inspect
puts "v1 characteristics: ", v1.characteristics.map(&:name).inspect
__END__
Output will be like
g1:
#<Grouping id: 7, name: "group g1">
g1 characteristics:
["characteristic c1", "characteristic c2"]
c1 values:
["value v1"]
v1 characteristics:
["characteristic c1", "characteristic c2"]
create table characteristics (
id serial primary key,
name varchar
);
create table groupings (
id serial primary key,
name varchar
);
create table values (
id serial primary key,
name varchar
);
create table groupings_values (
grouping_id integer references groupings(id) on delete cascade,
value_id integer references values(id) on delete cascade
);
create table characteristics_groupings (
characteristic_id integer references characteristics(id) on delete cascade,
grouping_id integer references groupings(id) on delete cascade
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment