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?
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]
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 =]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With