I would like to show you something more complicated, but i'm just starting to learn it myself. As a tester application, i'm rebuillding a simple time clock application I built for my office in php4. I can show you a little code from that.
Rails uses a type of Model View Controller approach to coding web apps. In rails the urls the browser requests are more or less mapped directly to methods defined in a controller class. For example in my application I have a user table. I create a user controller class with the following code.
class UserController < ApplicationController
model :user
scaffolding :user
end
These four lines of code do a lot of work for me. The line
mode :user ties this controller to the User model, and
scaffolding :user provides a basic framework for creating, updating, listing, and deleting users. I can already create or edit a record in the user table through the web with four lines of code. I will admit that the interface is ugly, and will probably have to be modified in 9 out of 10 cases.
So i'm unhappy with the information shown by the list method in the UserController. I can easily change it by "overriding" the list method in the UserController. All the method has to do is load a data structure with the users in the database. So the UserController looks like this now:
class UserController < ApplicationController
model :user
scaffolding :user
def list
@users = User.find_all
end
end
So three more lines of code fill a list with all the user records in the table. In ruby if you customize the behavior of the default scaffolding code, you need to provide a view for the new method. Here's the view below:
Timeclock users
Time Clock Users
Action |
Username |
Name |
User Type |
<% @users.each do |@user| %>
<%= link_to("View", :action => "show", :id => @user.id) %> |
<%= @user.user_name %> |
<%= @user.first_name + ' ' + @user.last_name %> |
<%= @user.user_type %> |
<% end %>
This iterates over the instance variable @users and prints an edit link, user_name, name, and user type in an extremely simple html page.
So the url:
http://timeclock/user/list now points to my new "list template" just like
http://timeclock/user/edit/1 points to the edit page for the user with id 1.
Still have a lot to learn, but so far it's been easy to pick up. I like the fact that the control flow of the application is already done for you. no more large switch statements or action variables.
More later