The use of generators
is debated in Rails; some say that they are a useful way to get code
up and running, while others say they hide too many details and don??™t
allow enough flexibility. We will not debate the merits here; we simply
use the generator to build a simple application without letting the details
get in the way.
First, we create the Rails application skeleton:
$ rails products_example
create
create app/controllers
create app/helpers
...
create log/production.log
create log/development.log
create log/test.log
$ cd products_example
Then, after setting up our development database information, we use the scaffold
generator to create the model, controller, and sample templates all at once for the
Product model. The generator will set up the appropriate fields in the database if
they are provided on the command line:
$ script/generate scaffold product \
name:string description:text price:float quantity:integer \
created_at:datetime
exists app/models/
exists app/controllers/
exists app/helpers/
...
create db/migrate
create db/migrate/001_create_products.rb
route map.resources :products
$ rake db:migrate
== CreateProducts: migrating ==================================================
-- create_table(:products)
-> 0.0746s
== CreateProducts: migrated (0.0747s) =========================================
In practice, prices should not be stored as floating-point values; rather,
they should be stored as integers in the lowest-common-denominator
unit of currency (such as cents when the currency is U.
Pages:
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353