Lost Password?
Register now!
Page « 1 ... 3 4 5 (6) 7 8 9 »
Articles : Web Development Using the Ruby on Rails
on 2008/7/27 23:54:31 (2893 reads)

Employee is the class we saw in the previous chapter about the Model layer. It class method 'find' takes various parameters, in this case params[:id]. The parameter 'params' is a map that contains all incoming parameters, be it from an url, a GET or a POST. Rails collects these on each incoming request, another annoyance the developer doesn't have to worry about anymore! The right part of the assignment can now be explained as: find the employee whose id is in the value of params[:id], which is 1 as specified in the example link.

On the left part we have '@employee'. The '@' in front of the variable means that we want to make it a class variable. In Ruby we don't have to declare the variable first, it exists as soon as we put something in it. When you put something in a class variable, it means you want to make the variable available to the view layer. We want to show the data of an employee on a Web page (the view) so the result of the Employee.find method is put in the class variable @employee.

It looks like we're done now because there is no code left, but there is still one thing left to do: show to the user the information we loaded from the database. If we don't state explicitly in the action what has to happen after executing the action, Rails assumes, correctly in this case, that we want to load a new Web page in the application. Rails needs an html page (well it's a bit more as plain html but we'll see that in the next part) to render the Web page. This is already been taken care of by yet another naming convention. All Web pages reside in a directory that Rails knows about, just like the directory that contains the models, the configuration, etc. In this directory, Rails looks for a subdirectory with the same name as the controller, 'employees' in this case, and then looks for a file with the same name as the action, 'show'. This is an overview of the file layout (I omitted the irrelevant folders):


employees_controller.rb-> the controller + .rb extension (Ruby source)

employee.rb -> the model + .rb extension (Ruby source)


/employees -> the name of the controller
show.rhtml > the name of the action + .rhtml extension (Rails html file)

These directories are generated by Rails at the time you setup the project.

Another example to illustrate these principles:

class ContractsController < ApplicationController

def destroy

contract = Contract.find_by_number(params[:number]
# removes the row that contains the contract redirect_to 'show'

@contracts = Contract.find(:all)


Page « 1 ... 3 4 5 (6) 7 8 9 »
Printer Friendly Page Send this Story to a Friend Create a PDF from the article