I followed a tutorial step by step which resulted in what has been,
me, the holy grail: a one-to-many relationship. A screenshot of what
ended up with:
Name: Chili Cookoff
Edit | Back
2007-12-09 Fire Department $25.00
2007-12-10 Parties R Us $75.00
demonstrating the "many" expenses per accounts; a "one-to-many"
relationship with CRUD interface.
The step which was most mysterious in the tutorial:
"Generate the scaffolding by typing
$ script/generate scaffold account expenses
That command generates a number of files for us; files we'd rather
create by hand. The first parameter (account) specifies the name of
model, which is generated in the app/models/account.rb file. The
parameter (expenses) specifies the name of the controller, which is
generated in the app/controllers/expenses_controller.rb file. The
scaffold generator also created template files for the views of our
This is all well and good, but the choice for the singular versus
choice is unclear to me. Both models are singular, as expected.
then, is it "expenses" and not "expense" in the above scaffold
Is this significant, a typo, or is the name of the scaffold here
It strikes me that there's an intuitive mismatch between navigating
<http://localhost:3000/expenses> and being presented with a listing
Chili Cookoff 150.0 Show Edit Destroy
Car Wash 25.0 Show Edit Destroy
Pancake Breakfast 125.0 Show Edit Destroy
Dunk the Programmer 50.0 Show Edit Destroy
rather than a listing of expenses.
Which brings me to my next question: what's the connection between
model name, Expense, and the name of this particular controller,
expenses_controller.rb? Could it have been "script/generate scaffold
account foo", or was it critical that "expenses" match up with the
"$ rake migrate
Next we need an Expense model to wrap the expenses table. Use the
generator to create the model by typing
$ script/generate model expense
That command gives us an empty Expense model class. Now we have to
tell Rails that a relationship exists between the accounts and
expenses tables. (Rails can't accurately derive relationships simply
by looking at the database schema.) Specifically, an expense belongs
to an account. Declare that relationship in the Expense model by
updating the app/models/expense.rb file as follows:
class Expense < ActiveRecord::Base
Ok, the above makes sense, except for: why the choice to run "script/
generate model" versus they initially ran "script/generate migration"?
For the Accounts model they used a migration, but for expenses they
use "generate model"; why?