Page 13      All Pages  All Books
def edit
@category = Category.find(@params['id']) end
def update
@category = Category.find(@params['category']['id']) if @category.update_attributes(@params['category'])
flash['notice'] = 'Category was successfully updated.' redirect_to :action => 'show', :id => @category.id else
render_action 'edit' end end
def destroy
Category.find(@params['id']).destroy
redirect_to :action => 'list' end end
The default action for the controller is to render a template matching the name of the action e.g. the list action will populate the @categories instance variable and then the controller will render "list.rhtml". render_template allows you to render a different template e.g. the index action will run the code for list, and will then render list.rhtml rather than index.rhtml (which doesn’t exist) redirect_to goes one stage further, and uses an external “302 moved” HTTP response to loop back into the controller e.g. the destroy action doesn’t need to render a template. After performing its main purpose (destroying a category), it simply takes the user to the list action.
Documentation: ActionController::Base
The controller uses ActiveRecord methods such as find, find_all, new, save, update_attributes, and destroy to move data to and from the database tables.
Documentation: ActiveRecord::Base
Notice how several of the actions are split into two. For example, when the user selects edit, the controller extracts the record they want to edit from the model, and then renders the edit.view. When the user has finished editing, the edit view invokes the update action, which updates the model and then invokes the show action.
Tailoring the default Controller
Personally, I don’t like the way Rails displays the show screen next I prefer to go straight back to the list screen; the show screen isn’t necessary in this application. However, it would be nice to display a message to say the edit has worked:
app\controllers\categories_controller.rb (excerpt)
def update
@category = Category.find(@params['category']['id']) if @category.update_attributes(@params['category'])
flash['notice'] = 'Category was successfully updated.' redirect_to :action => 'list' else
render_action 'edit' end end
The flash message will be picked up and displayed on the next screen to be displayed in this case, the list screen (see Tailoring the default ‘List’ View on page 12).
Documentation: ActionController::Flash
Curiously, although the flash message has its own css tag, the stylesheet produced by the generate scaffold script doesn’t do anything special with it. This is solved by a simple addition:
Page 9

Page 13      All Pages  All Books