Monthly Archives: March 2014

Phone extension manager app coming soon

Am currently in the process of tidying up my application for managing telephone extensions for synchronising with a telephony system so that I can post the code on GitHub.

I can then do more work on another application for temporary account access management and start planning an application to interface with a security swipecard management system (though I probably will have a new hire write that one).

 

Re-raising Rails model errors

On my current project I’ve had occasions when I have coded a particular feature which has resulted in just a blank page being displayed, no content and no errors reported in the development log.

The only hints come from the queries that the development log; the view templates are using class methods on external models and running some of the queries by hand shows them returning no rows.

With a model method like,

def self.building_name(id)
  b = Building.find(id
  "#{b.name}"
end

being used in the view

<td><%= Building.building_name(room.building_id) %></td>

Now, it turns out the building_id value doesn’t have a matching record in the parent table (and, yes, I will use FK constraints once the very messy data is fixed, Rails dogma be damned) but no errors being thrown and template processing silently ceased.

I had been looking at trying to improve my error reporting using rescue_from in the application_controller and disappointed to discover (via A GitHub posting from Ryan Bates) that a file render called from a method here has to be static HTML and so can’t include the exception message.

But the same posting made mention of using a redirect.

So, my class method can be tweaked to trap when no rows are returned

def self.building_name(id)
   begin
     b = Building.find(id)
   rescue
     Rails.logger.error "Error locating building with id #{id}."
     raise ActiveRecord::RecordNotFound, "Cannot locate building with id #{id}."
   end
   "#{b.name}"
 end

And my application controller contains,

  rescue_from ActiveRecord::RecordNotFound, with: :no_record_errors
  ...
  protected
  def no_record_errors(exception)
     redirect_to root_url, :alert => "Missing record error #{exception.message}."
   end

Which fires me back to the front page with a very clear and simple error message and no blank page.

One final consequence of this was that since I’m also using session variable to store the state of simple searches in the application, on several occasions it was impossible to recover from the blank page scenario.

But raising the (non) error also gives the opportunity to clear down session values that reinforce this condition and return the application to a fail safe condition. Very pleasing.