Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #1349: bad-callbacks.rb

File bad-callbacks.rb, 1.3 kB (added by minam, 3 years ago)

A minimal script to duplicate the problem

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