Merge pull request #305 from albertsun/safer-add-event-id-at-creation-to-links-migration

Small fix for the AddEventIdAtCreationToLinks migration

Andrew Cantino 10 年之前
父节点
当前提交
c8f29fef39
共有 1 个文件被更改,包括 18 次插入8 次删除
  1. 18 8
      db/migrate/20140213053001_add_event_id_at_creation_to_links.rb

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

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