| 1 |
require 'active_record' |
|---|
| 2 |
|
|---|
| 3 |
ActiveRecord::Base.establish_connection( |
|---|
| 4 |
:adapter => "sqlite3", |
|---|
| 5 |
:dbfile => ":memory:" |
|---|
| 6 |
) |
|---|
| 7 |
|
|---|
| 8 |
DATA.read.split(/;/).each do |sql| |
|---|
| 9 |
next if sql.strip.blank? |
|---|
| 10 |
ActiveRecord::Base.connection.execute(sql) |
|---|
| 11 |
end |
|---|
| 12 |
|
|---|
| 13 |
class Project < ActiveRecord::Base |
|---|
| 14 |
has_and_belongs_to_many :people |
|---|
| 15 |
|
|---|
| 16 |
after_create :grant_to_harry_potter |
|---|
| 17 |
|
|---|
| 18 |
protected |
|---|
| 19 |
def grant_to_harry_potter |
|---|
| 20 |
harry = Person.find_by_name('harry potter') |
|---|
| 21 |
harry.projects.push_with_attributes(self, 'access_level' => 42) |
|---|
| 22 |
end |
|---|
| 23 |
end |
|---|
| 24 |
|
|---|
| 25 |
class Person < ActiveRecord::Base |
|---|
| 26 |
has_and_belongs_to_many :projects |
|---|
| 27 |
end |
|---|
| 28 |
|
|---|
| 29 |
harry = Person.find_by_name('harry potter') |
|---|
| 30 |
rand = Person.find_by_name("rand al'thor") |
|---|
| 31 |
|
|---|
| 32 |
project = Project.new :name => "sumo wrestling" |
|---|
| 33 |
|
|---|
| 34 |
|
|---|
| 35 |
project.people << rand |
|---|
| 36 |
|
|---|
| 37 |
project.save! |
|---|
| 38 |
project.reload |
|---|
| 39 |
|
|---|
| 40 |
puts "after saving:" |
|---|
| 41 |
puts " has rand al'thor: #{project.people.include?(rand)} (should be true)" |
|---|
| 42 |
puts " has harry potter: #{project.people.include?(harry)} (should be true)" |
|---|
| 43 |
|
|---|
| 44 |
__END__ |
|---|
| 45 |
CREATE TABLE projects ( |
|---|
| 46 |
id integer primary key, |
|---|
| 47 |
name varchar(40) |
|---|
| 48 |
); |
|---|
| 49 |
|
|---|
| 50 |
CREATE TABLE people ( |
|---|
| 51 |
id integer primary key, |
|---|
| 52 |
name varchar(40) |
|---|
| 53 |
); |
|---|
| 54 |
|
|---|
| 55 |
CREATE TABLE people_projects ( |
|---|
| 56 |
project_id integer not null, |
|---|
| 57 |
person_id integer not null, |
|---|
| 58 |
access_level integer not null default 0 |
|---|
| 59 |
); |
|---|
| 60 |
|
|---|
| 61 |
INSERT INTO people VALUES (1, 'harry potter'); |
|---|
| 62 |
INSERT INTO people VALUES (2, 'rand al''thor'); |
|---|