20140213053001_add_event_id_at_creation_to_links.rb 834 B

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