Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

224 | Chapter 7: REST, Resources, and Web Services


We will be using thescaffoldgenerator (formerlyscaffold_resource)to
build some quick RESTful templates for the interface. The use of genera-
tors 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 thescaffold
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.S. dollars). The
Money gem by Tobias Lütke (gem install money) makes this easier in
Rails.

After migrating and tweaking the forms a bit, we have a very simple CRUD applica-
tion for products. Starting the server withscript/server, we can see an empty list at
http://localhost:3000/, as shown in Figure 7-1.

Free download pdf