Rails: Automatic Time Stamping

I tried this with mySQL. Should work with other databases too.

If you have columns named “created_at” or “updated_at” of type datetime in your database table,
Rails will automatically insert the value of now( ), in the column “created_at” when a model corresponding to the table is saved in the database. Similarly it will automatically update the value of the column “updated_at” to the value of now( ), when a model is updated and saved to the database.

“created_on” and “updated_on”, of type date, display the same functionality.

One of the basic Rails philosophy is “Convention over Configuration”, meaning that rails has sensible defaults for a lot of aspects.

If the programmer follows these naming conventions a lot of functionality in the application gets built-in by default.

Rails: avoid empty lines in generated html

Normally embedded Ruby code (Erb) in views that does not generate any output, leaves empty blank lines in the generated HTML code. These are embedded ruby lines in rhtml files which begin with < % and not <%=. To avoid generating these empty blank lines, end the embedded ruby code with -%>, the others will be ended as %>. The extra minus sign (-) at the end, will suppress the blank lines.

Rails: Escaping html entities

Many times data entered on the screen by a user, or data fetched from the db, contains less than (<), greater than (>), ampersand (&) and quotes etc. These characters have special meaning in html. And if these are passed in the view as such, they may garble the browser display.

The h() method prevents these characters in strings from garbling the browser display. The h() method escapes them as html entities.

h() method in rails does the same thing as htmlentities() does in php.

Update [17th Jan 2006] I just learnt that long name of h() is html_escape()

Customizing Rails validation error messages

Rails Version information: activerecord-1.12.1, rails-0.14.1

I have a form, where the user enters a name, “johndoe”. I already have a user “johndoe”, and i want user name to be unique.
The default error message that validate_uniqueness_of returns is “Name is already taken”
But I want “Name johndoe is not available”.

Here is my user model, user.rb file, with the custom message.

Read more

Ruby on Rails

It took me ten minutes flat to get my first mini application running. A basic screen to view and edit a database table content using a browser. Much of it was done by the code generating scripts that come with RoR. I still have to explore the more involved features…. have heard a lot about RoR’s unit testing features and… will check it out soon.