4.8 Creating Controllers ( Action Controller )
We had created a model. Now we will create a controller and
afetr we will create the view.
The syntax to create a controller, according to the Rails rules
to capitalize and use the singular form for the related
model, for Hydrocarbon model is:
C:\ruby\organics\> ruby script/generate controller Hydrocarbon
C:\ruby\organics\> ruby script/generate controller Group
That creates the file:
C:\ruby\organics\app\controllers\hydrocarbon_controller.rb
Now, we will set some definitions inside that file, as follows:
class HydrocarbonController < ApplicationController
def list
@hydrocarbons = Hydrocarbon.find(:all)
end
def display
@hydrocarbon = Hydrocarbon.find(params[:id])
end
def display_groups
@group = Group.find(params[:id])
end
def new
@hydrocarbon = Hydrocarbon.new
@groups = Group.find(:all)
end
def create
@hydrocarbon = Hydrocarbon.new(params[:hydrocarbon])
if @hydrocarbon.save
redirect_to :action => 'list'
else
@groups = Group.find(:all)
render :action => 'new'
end
end
def edit
@hydrocarbon = Hydrocarbon.find(params[:id])
@groups = Group.find(:all)
end
def update
@hydrocarbon = Hydrocarbon.find(params[:id])
if @hydrocarbon.update_attributes(params[:hydrocarbon])
redirect_to :action => 'display', :id => @hydrocarbon
else
@groups = Group.find(:all)
render :action => 'edit'
end
end
def remove
Hydrocarbon.find(params[:id]).destroy
redirect_to :action => 'list'
end
end
|