views:

151

answers:

1

I'm new to Ruby on Rails, and I'm trying to create a bass guitar tutor in order to teach myself RoR (and bass guitar). The walkthroughs use Scaffold to create ActiveRecord classes, but they seem to correspond to standalone tables; there's no use of belongs_to or has_many.

I'd like to create three classes: Scale, GuitarString, and Fret. Each Scale has many GuitarStrings, which each have many Frets.

How do I create classes with this relationship using Scaffold? Is there a way to do it in one go, or do I need to create them in an unrelated state using Scaffold, then add the relations by hand? Or should I ditch Scaffold entirely?

+1  A: 

I started learning Ruby on Rails a few weeks ago, and I've found it a lot easier to get the hang of things and learn my way around by not using scaffolding, and generating the various parts from the command line (or macros in an IDE).

However, from what I can tell, when you use scaffolding to generate things, you think of it as generating a "resource", so you're only going to create one resource at a time, then add in the relationships by hand later.

However, the generate model command can create these relationships for you. Lets say you used scaffolding to create a Scale resource.

You could then do

ruby script/generate model GuitarString name:string scale:references 

The scale:references will create a belongs_to :scale on your GuitarString model, but you'll need to add has_many :guitarstrings to your scale model.

The generate model command also creates a migration script for you and other files needed (fixtures), similar to scaffolding, but doesn't autocreate views or controllers or anything.

EDIT:

This is generally how you are going to want to do things - use the generate/model or generate/view or generate/controller or generate/migration. Most Rails developers don't use scaffolding, since its "one size fits all" rarely fits things perfectly. However, most rails developers do use the generate commands I mentioned - it saves time with creating helpers and fixtures by hand, and it gives each file it generates a basic template you can add to.

Several Ruby IDE's like JetBrain's RubyMine have macros that essentially perform these commands. In RubyMine you can do ctrl+alt+g, then enter another key corresponding to what you want to generate.

The belongs_to relationship can be generated by using the "references" word, as I mentioned. Others you will add in by hand.

Zachary