Skip to content

Instantly share code, notes, and snippets.

@averyvery
Created April 11, 2012 19:27
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save averyvery/2361682 to your computer and use it in GitHub Desktop.
Save averyvery/2361682 to your computer and use it in GitHub Desktop.
Seeding images in Rails
# encoding: utf-8
environment_seed_file = File.join(Rails.root, 'db', 'seeds', "#{Rails.env}.rb")
def seed_image(file_name)
File.open(File.join(Rails.root, "/app/assets/images/seed/#{file_name}.jpg"))
end
products = [
{:name => 'foo', :description => 'lorem ipsum', :product_type => ProductType.find_by_name('Sandwiches')},
{:name => 'bar', :description => 'dolerem ipsum', :product_type => ProductType.find_by_name('Soups')}
]
products.each do |attributes|
attributes[:image] = seed_image('product_family_or_system')
Product.find_or_create_by_name(attributes[:name], attributes)
end
@averyvery
Copy link
Author

Also worth noting that if you want to add a WHOLE bunch of properties to everything you seed, with a few overrides, you can merge from some default attributes:

products.each do |overrides|
  attributes = {
    :family => Family.find_by_name('Roast Beef),
    :product_type => ProductType.find_by_name('Sandwiches'),
    :description => 'Delicious.',
    :main_image => seed_image('product'),
    :list_image => seed_image('product_list')
  }
  attributes.merge!(overrides)
  Product.find_or_create_by_name(attributes[:name], attributes)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment