views:

38

answers:

2

Hi folks,

Just meddling with Rails at the moment, and struggling to figure out how to escape "you have a nil object when you didn't expect it" errors . At the moment I'm escaping each of them with an "unless object.nil?" message, but it's getting pretty ugly. Case in point:

unless params[:professiontypeinfo].nil?
  unless params[:professiontypeinfo][professiontypeid].nil?
    unless params[:professiontypeinfo][professiontypeid]["industrybodies"].nil?
        @professional.professional_specialties.find_by_profession_type_id(professiontypeid).industry_bodies = IndustryBody.find_all_by_id(params[:professiontypeinfo][professiontypeid]["industrybodies"])
    end
  end
end

Soo...what's the correct/graceful way of escaping these things?

+2  A: 

The below method will evaluate each condition in order and exit if a condition fails without moving onto the next

unless params[:professiontypeinfo] && params[:professiontypeinfo][professiontypeid] && params[:professiontypeinfo][professiontypeid]["industrybodies"]

Update: based on Jimmy's comments =]

Coderama
removing the .nil? call will work as expected
Jimmy
+4  A: 

Hash[] returns false when the requested key is missing, so

if params[key]

will return false if params does not have key

And-ed conditions short-circuit (ie stop evaluating when the first condition is false), so the following will work even when key is missing:

if params[key] && params[key][sub_key]
zetetic