Last active
February 1, 2019 17:04
-
-
Save rmm5t/986af576602fc203bd64d39fbf0ee00a to your computer and use it in GitHub Desktop.
Example of idempotent seeds:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Author: Ryan McGeary : http://github.com/rmm5t | |
# License: MIT : https://rmm5t.mit-license.org/ | |
def restart_sequence(klass) | |
seq = [klass.table_name, "id", "seq"].join("_") | |
next_id = klass.maximum(:id) + 1 | |
klass.connection.execute "ALTER SEQUENCE #{seq} RESTART #{next_id}" | |
end | |
def load_seed_data(klass, records) | |
bar = ProgressBar.create(title: "#{klass} seeds", total: records.length) | |
records.each do |record| | |
o = klass.find_or_initialize_by(id: record[:id]) | |
o.update!(record) | |
bar.increment | |
end | |
restart_sequence(klass) | |
bar.finish | |
end | |
load_seed_data( | |
BroadcastType, | |
[ | |
{ id: 1, name: "None" }, | |
{ id: 2, name: "AM" }, | |
{ id: 3, name: "FM" }, | |
{ id: 4, name: "FM HD2" }, | |
{ id: 5, name: "FX FEED" }, | |
] | |
) | |
load_seed_data( | |
ContentType, | |
[ | |
{ id: 1, name: "Not Defined" }, | |
{ id: 2, name: "Music" }, | |
{ id: 3, name: "News/Talk" }, | |
{ id: 4, name: "Sports" }, | |
] | |
) | |
load_seed_data( | |
Genre, | |
[ | |
{ id: 1, name: "Adult Contemporary" }, | |
{ id: 2, name: "Classical" }, | |
{ id: 3, name: "Country" }, | |
{ id: 4, name: "Family" }, | |
{ id: 5, name: "Hip Hop/Urban" }, | |
{ id: 6, name: "Jazz/Blues" }, | |
{ id: 7, name: "News/Talk" }, | |
{ id: 8, name: "Oldies" }, | |
{ id: 9, name: "R&B" }, | |
{ id: 10, name: "Religious" }, | |
{ id: 11, name: "Rock" }, | |
{ id: 12, name: "Spanish" }, | |
{ id: 13, name: "Sports" }, | |
{ id: 14, name: "The Decades" }, | |
{ id: 15, name: "Top 40/Pop" }, | |
{ id: 16, name: "World/Variety" }, | |
{ id: 17, name: "Comedy" }, | |
{ id: 18, name: "NPR" }, | |
] | |
) | |
# ... | |
# ... | |
# ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment