Created
February 28, 2011 23:39
-
-
Save HotFusionMan/848285 to your computer and use it in GitHub Desktop.
Generic YAML fixture loader for Rails. Supply a db/seeds.yaml file containing fixtures with sections named for their ActiveRecord models, pluralized (e.g., Queries). Invoke with rake db:seed.
This file contains hidden or 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
# Based on http://stackoverflow.com/questions/2339021/how-can-i-load-some-activerecord-models-from-a-yaml-file-and-save-them-to-the-db/ | |
seed_filepath = File.join( RAILS_ROOT, 'db', 'seeds.yaml' ) | |
config = YAML::load_file( seed_filepath ) | |
config.each { |pluralized_model_name, fixtures| | |
model_class = pluralized_model_name.singularize.constantize | |
# If you like leaping without looking: | |
# model_class.create( fixtures ) | |
fixtures.each { |fixture| | |
# Presumably, it's silly to try to set the Rails numeric id fields explicitly, so delete those columns from the fixture. | |
fixture.delete( 'id' ) | |
# fixture.keys.each { |column_name| | |
# if column_name =~ /_id\Z/ then | |
# fixture.delete( column_name ) | |
# end | |
# } | |
# See if there are any existing records that are identical to the fixture we're about to create a record from, and if not, create it. | |
method_name_parts = [] | |
arguments = [] | |
fixture.each { |column_name, value| | |
method_name_parts << column_name | |
arguments << value | |
} | |
method_name = 'find_by_' << method_name_parts.join( '_and_' ) | |
unless model_class.__send__( method_name.intern, *arguments ) | |
model_class.create( fixture ) | |
end | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment