Jonathan Jonathan - 1 year ago 81
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:


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

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


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


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

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

Answer Source

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)

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download