Newbie rails question: an elegant way to handle null values ​​in .each loops?

Just interfering with Rails at the moment, and struggling to figure out how to avoid "you have a null object when you did not expect this." At the moment I am running away from each of them with "if object.nil?" message, but it gets pretty ugly. Example:

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

Su ... what is the right / elegant way to avoid these things?

+3
source share
2 answers

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

if params[key]

will return falseif paramsnotkey

(.. , ), , key :

if params[key] && params[key][sub_key]
+4

, ,

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

: =]

+2

Source: https://habr.com/ru/post/1769067/


All Articles