Advancing with Rails, day 2

Posted on April 14, 2008
Filed Under Rails, Ruby, Web |

I had hoped to post a daily updates on the rest of the 'Advancing with Rails course the week before last, but alas, life was a little too busy so here's what I particularly enjoyed on day 2.

Rails is all about the request cycle

Your application is basically just sitting there waiting for a request. When you send one, it responds then returns to its resting state. To be honest I'd never really given this much thought but it makes sense.

Your controller is your application

The controller is the thing that directs all of the actions, handing things off to other controllers / querying the model. Controllers have access to the whole application domain, can dip in an out of models as they please.

Redirect vs render

This is something that I'd never fully realised. When you

redirect_to => "action"

in your controller, you're actually starting a new request cycle. Crucially this means that all instance variables are reset. I've often found myself doing something like this in a controller:


def update
  if something
    success
  else
    redirect_to :action => "edit", :id => @item
  end
end

If we were updating an item with a form and there had been an error caught by and ActiveRecord validation, the redirect would stop the error from showing up as the @item instance variable is reset when calling the redirect_to.

An alternative to this is the render method. Instead you can do this:


...
  else
    render :action => "edit"
  end
end

This means that the instance variables are kept the same (i.e. not reset) and so errors would show up properly.

This is one of those things where experience had taught me to use a render rather than a redirect, but again, it was great to have it spelled out and explained fully.

Custom validations

It's possible to define a custom protected method called validate inside your models. Using this method you can add an error message on a particular field. In the case below, returning the error "Looser" if the name field equals "matt".


protected

def validate
  errors.add(:name, "Looser") if name = "matt"
end

Another possibility is to have an 'inline' validation as follows:

validates_format_of :name, :with => some regex here, :message => "I don't think much of that name"

This is a good way of checking the format of a field, for example an email address.

Interestingly, every ActiveRecord object has an errors structure. If object.errors is empty then the object is valid (and will save).

After this we went into some hardcore Ruby hacking, but my eyes are too tired for all that now so more later…

Comments

Leave a Comment

If you would like to make a comment, please fill out the form below.

You must be logged in to post a comment.

Recently


Categories


Archives