@@ -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 |