Ruby on Rails in a day.
2012 April 19 at 00:39 » Tagged as :ruby, ror, sqlite, blackbox, scaffold,
Raills apps follow the Model View Controller design pattern. At the heart of the Model is the ActiveRecord
class which in turn is based on the ActiveRecord design pattern and the Single Table Inheritance pattern. Interestingly there is an ActiveRecord implementation for PHP inspired by the one in Ruby. ActiveRecord
comes with validators to ensure data intergrity
The View is Represented by the ActionView
which comes bundled with an embedded templating system; ERB. With in the files that make up your view, you can mix HTML (or JSON or XML) and code pretty much the same way you do with JSP or PHP
ActionController
as the name suggests represents the Controller, it comes with a bunch of stuff like session management, logging and filters.
Seems like most rails books, the tutorials are also keen to get you started on creating a first app. Which means you run into a few black boxes early on. For example rails three in a nutshell has the following:
rails generate scaffold Video title:string embed_code:text
There isn't an explaination of what this command really does or what the parameters are, but by running `rails generate scaffold --help
` I gathered the following.
Pass the name of the model (in singular form), either CamelCased or under_scored, as the first argument, and an optional list of attribute pairs.
Attributes are field arguments specifying the model's attributes. You can optionally pass the type and an index to each field.
The db/migrate folder has a timestamped file which needs to be processed with rake,
Ruby's alternative to make , in order to create the database (which in this case is on Sqlite). One advantage of this approach is that database changes are very easy to version control but in fact, you don't need to do so because you can read through the files in order that they were created to figure out what changes were actually made.
We have already discussed that ActiveRecord
doesn't charge you any money for data validation. But it's a special offer, limited to the functions given below (the RoR guide):
create and create! save and save! update update_attributes and update_attributes!
If you create an object with new
, you don't get free validation. Save
will also skip validation if you pass :validate => false as as an argument. You also need to tell active record what should be validated using the validates keyword (eg validates :title, :embed_code, :presence => true). You can also name a custom validation method using the validate keyword. Its also possible to specify whether a variable is a number a string, empty or not, set a maximum and a minimum and a lot more things besides.