Created
September 9, 2009 01:43
-
-
Save erithmetic/183394 to your computer and use it in GitHub Desktop.
Quick and Dirty Rails Seeding
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
# Save as db/seed.rb | |
# | |
# Run with script/runner db/seed.rb | |
def unique_attributes | |
{ | |
MyModel => [:name], | |
MyOtherModel => [:category, :type] | |
} | |
end | |
def seed(klass, attributes) | |
conditions = unique_attributes[klass].inject({}) do |hsh, attribute| | |
hsh[attribute] = attributes[attribute] | |
hsh | |
end | |
if klass.find(:first, :conditions => conditions).nil? | |
puts "Creating #{klass} #{attributes.inspect}" | |
klass.create!(attributes) | |
end | |
end | |
seed(MyModel, | |
:name => "Shirt", | |
:price => 5.00, | |
:order => 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment