Main Content

Really Simple Rails

Archive - Originally posted on "The Horse's Mouth" - 2013-02-17 12:29:10 - Graham Ellis

Rails is a "Web Framwork" that uses code written in the Ruby language to do the things that vary from one web application to another. There are a huge number of features common to many web applications, and by using a framework you can save yourself the trouble of rewriting all these common things, using instead what's provided by Rails. It makes for quicker coding, a well thought out structure from the beginning, but (conversely) a whole lot of hooks and special names and terminologies that will leave the newcomer gasping for breath at first.

A very first demonstration of how the elements go together - see my previous blog [here] - about how examples can get overcomplicated before they're published. I don't pretend that this is useful in production, or clever, or even well structured - but it does show you how values from your model reach your view.

Background ... a new Rails application, installed and built using the Rails Installation Cheat Sheet I wrote a while back. That cheat sheet sets you up with a running new application that does nothing on rails.

Then set up
a) Application called "serverstats"
b) Controller called "summarise"
c) Model called "access"

  rails serverstats
  cd serverstats
  script/generate controller summarise
  script/generate model access ip:string pagename:string


Now - what URL do I use to browse to that? Answer: /summarise/ (and it will tell you there is no route). So I want to set up a controller and a view. See [here] for the directorys / files needed - and you only need the controller
  app/controllers/summarise_controller.rb
and the view
  app/views/summarise/index.erb
to start you off (in fact the index method in the controller can be empty at first, and the view template can contain just HTML).

The example code goes on to show you how you can add each of the following to your view
a) The standard (static) view
b) Data calculated in the view (you shouldn't do much of this)
c) Data to be displayed / calculated by the controller
d) Class data and application level information from a model
e) Database information provided through the model

For the database section to work, you'll want to add some seed values (see sample file) and you'll then need to:
  rake db:migrate
  rake db:seed
to set up and provide some initial test values in your database. Rails will default to SQLite.

Rails varies a bit from version 2 to 3 ... and at the time of writing, 4's on its way. At the end of our Ruby Programming Course we offer an optional Introduction to Ruby on Rails which will help you with your first steps into this framework, as in the example above.