Skip to content

Instantly share code, notes, and snippets.

@erithmetic
Created September 9, 2009 01:43
Show Gist options
  • Save erithmetic/183394 to your computer and use it in GitHub Desktop.
Save erithmetic/183394 to your computer and use it in GitHub Desktop.
Quick and Dirty Rails Seeding
# 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