in the AddEventIdAtCreationToLinks migration, handle the case of links that don't yet have any events

Albert Sun 10 years ago
parent
commit
15b55ac371
1 changed files with 14 additions and 8 deletions
  1. 14 8
      db/migrate/20140213053001_add_event_id_at_creation_to_links.rb

+ 14 - 8
db/migrate/20140213053001_add_event_id_at_creation_to_links.rb

@@ -2,14 +2,20 @@ class AddEventIdAtCreationToLinks < ActiveRecord::Migration
2 2
   def up
3 3
     add_column :links, :event_id_at_creation, :integer, :null => false, :default => 0
4 4
 
5
-    execute <<-SQL
6
-      UPDATE #{ActiveRecord::Base.connection.quote_table_name('links')}
7
-      SET event_id_at_creation = (
8
-        SELECT #{ActiveRecord::Base.connection.quote_column_name('id')}
9
-        FROM #{ActiveRecord::Base.connection.quote_table_name('events')}
10
-        WHERE events.agent_id = links.source_id ORDER BY events.id DESC limit 1
11
-      )
12
-    SQL
5
+    Link.all.each do |link|
6
+      last_event_id = execute(
7
+        <<-SQL
8
+          SELECT #{ActiveRecord::Base.connection.quote_column_name('id')}
9
+          FROM #{ActiveRecord::Base.connection.quote_table_name('events')}
10
+          WHERE events.agent_id = #{link.source_id} ORDER BY events.id DESC limit 1
11
+        SQL
12
+      ).first.to_a.first
13
+      if last_event_id.nil?
14
+        link.event_id_at_creation = Event.last.id
15
+      else
16
+        link.event_id_at_creation = last_event_id
17
+      end
18
+    end
13 19
   end
14 20
 
15 21
   def down