Jonathan Jonathan - 6 months ago 19
Ruby Question

Seeding Categories and Subcategories

I'm trying to seed my database with static categories (e.g. Men's / Women's) then have sub categories which belong to these categories but I actually don't know how to go about doing this with database seeding.

I've got models set up like so:

Category.rb

class Category < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged

has_many :subcategories
has_many :products ,:through => :subcategories
end


Subcategory.rb

class Subcategory < ActiveRecord::Base
belongs_to :category
has_many :products
end


Product.rb

class Product < ActiveRecord::Base
acts_as_taggable
extend FriendlyId
friendly_id :name, use: :slugged
belongs_to :subcategory
end


How would I go about writing a database seed to do this?

Answer

The first thing that comes to mind (at least mine) is to create local variables :

# db/seeds.rb
mens = Category.create(name: "Men's")
womens = Category.create(name: "Women's")
SubCategory.create(name: 'Slacks', category: mens)
SubCategory.create(name: 'Slacks', category: womens)

A nicer (No subcategory can be created apart from its category) solution is to use Model.create with a block :

Category.create(name: "Men's") do |category|
  Subcategory.create(name: 'Slacks', category: category)
end

then seed with the rake task : $ rake db:seed