Create EventTypes with data from existing Events

Use the STI column used until this moment to create new EventTypes and
assign them to their corresponding Events.
This commit is contained in:
Petko Bordjukov 2015-04-17 03:40:30 +03:00
parent 9f0886af1e
commit 6ee3195bef
3 changed files with 37 additions and 0 deletions

View File

@ -0,0 +1,18 @@
class CreateEventTypesForAllExistingEvents < ActiveRecord::Migration
def up
event_types = execute 'SELECT DISTINCT(events.type) as type_name, tracks.conference_id, events.created_at, events.updated_at FROM events INNER JOIN tracks ON tracks.id = events.track_id WHERE events.type NOT NULL GROUP BY type_name;'
event_types.each do |type|
execute "INSERT INTO event_types (conference_id, created_at, updated_at)
VALUES (#{type['conference_id']}, '#{type['created_at']}', '#{type['updated_at']}');"
event_type_id = execute('SELECT MAX(id) AS last_id FROM event_types;').first['last_id']
execute "INSERT INTO event_type_translations (event_type_id, locale, created_at, updated_at, name, description)
VALUES (#{event_type_id}, 'en', '#{type['created_at']}', '#{type['created_at']}', '#{type['type_name']}', 'None');"
end
end
def down
end
end

View File

@ -0,0 +1,5 @@
class AddEventTypeToEvents < ActiveRecord::Migration
def change
add_reference :events, :event_type, index: true, foreign_key: true
end
end

View File

@ -0,0 +1,14 @@
class PopulateEventTypeOfExistingEvents < ActiveRecord::Migration
def up
event_ids = execute('SELECT id FROM events WHERE type NOT NULL;').map { |row| row['id'] };
event_ids.each do |id|
event_type_id = execute("SELECT ett.event_type_id FROM events JOIN event_type_translations AS ett ON events.type = ett.name WHERE events.id = #{id};").first['event_type_id']
execute("UPDATE events SET event_type_id = #{event_type_id} WHERE id = #{id}");
end
end
def down
execute("UPDATE events SET event_type_id = NULL");
end
end