Sum in each loop when object might be nil












1















I'm trying to loop though a set of objects (people) and sum the values of a bunch of objects that belongs_to :person, for example to get the cumulative years of different types of experience of a group of people



@people.each do |person|

finance_experience_sum += person.finance_experience.value
management_experience_sum += person.manangement_experience.value
clerical_experience_sum += person.clerical_experience.value

end


However, sometimes I get this error when a person doesn't have a certain type of experience. What's the easiest way to fix this in my each loop?




undefined method `value' for nil:NilClass




I understand why I'm getting the error, but not sure what is the easiest way to get past it in this scenario










share|improve this question




















  • 1





    @phauwni have replied to your question please check.

    – Cryptex Technologies
    Jan 1 at 5:25











  • Can you share your models and relations? I'm missing something.

    – iGian
    Jan 1 at 9:57
















1















I'm trying to loop though a set of objects (people) and sum the values of a bunch of objects that belongs_to :person, for example to get the cumulative years of different types of experience of a group of people



@people.each do |person|

finance_experience_sum += person.finance_experience.value
management_experience_sum += person.manangement_experience.value
clerical_experience_sum += person.clerical_experience.value

end


However, sometimes I get this error when a person doesn't have a certain type of experience. What's the easiest way to fix this in my each loop?




undefined method `value' for nil:NilClass




I understand why I'm getting the error, but not sure what is the easiest way to get past it in this scenario










share|improve this question




















  • 1





    @phauwni have replied to your question please check.

    – Cryptex Technologies
    Jan 1 at 5:25











  • Can you share your models and relations? I'm missing something.

    – iGian
    Jan 1 at 9:57














1












1








1








I'm trying to loop though a set of objects (people) and sum the values of a bunch of objects that belongs_to :person, for example to get the cumulative years of different types of experience of a group of people



@people.each do |person|

finance_experience_sum += person.finance_experience.value
management_experience_sum += person.manangement_experience.value
clerical_experience_sum += person.clerical_experience.value

end


However, sometimes I get this error when a person doesn't have a certain type of experience. What's the easiest way to fix this in my each loop?




undefined method `value' for nil:NilClass




I understand why I'm getting the error, but not sure what is the easiest way to get past it in this scenario










share|improve this question
















I'm trying to loop though a set of objects (people) and sum the values of a bunch of objects that belongs_to :person, for example to get the cumulative years of different types of experience of a group of people



@people.each do |person|

finance_experience_sum += person.finance_experience.value
management_experience_sum += person.manangement_experience.value
clerical_experience_sum += person.clerical_experience.value

end


However, sometimes I get this error when a person doesn't have a certain type of experience. What's the easiest way to fix this in my each loop?




undefined method `value' for nil:NilClass




I understand why I'm getting the error, but not sure what is the easiest way to get past it in this scenario







ruby-on-rails






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 1 at 9:46









iGian

4,4692625




4,4692625










asked Jan 1 at 2:11









phauwnphauwn

87111




87111








  • 1





    @phauwni have replied to your question please check.

    – Cryptex Technologies
    Jan 1 at 5:25











  • Can you share your models and relations? I'm missing something.

    – iGian
    Jan 1 at 9:57














  • 1





    @phauwni have replied to your question please check.

    – Cryptex Technologies
    Jan 1 at 5:25











  • Can you share your models and relations? I'm missing something.

    – iGian
    Jan 1 at 9:57








1




1





@phauwni have replied to your question please check.

– Cryptex Technologies
Jan 1 at 5:25





@phauwni have replied to your question please check.

– Cryptex Technologies
Jan 1 at 5:25













Can you share your models and relations? I'm missing something.

– iGian
Jan 1 at 9:57





Can you share your models and relations? I'm missing something.

– iGian
Jan 1 at 9:57












2 Answers
2






active

oldest

votes


















2














You can do simply like these without using the each loop



finance_experience_sum = People.includes(:finance_experience).sum(:value)
management_experience_sum = People.includes(:manangement_experience).sum(:value)
clerical_experience_sum = People.includes(:clerical_experience).sum(:value)


Always used ruby on rails best practices and predefined methods of ruby.






share|improve this answer



















  • 1





    upvoted for reliable answer but need @people in place of People

    – ray
    Jan 2 at 11:07











  • need change in your profile link(experience section) for ajaydhande.github.io for carrier (need to be career)

    – ray
    Jan 2 at 11:09











  • Okay thanks for your suggestions

    – Cryptex Technologies
    Jan 2 at 11:11











  • @ray i will do that

    – Cryptex Technologies
    Jan 2 at 11:11











  • Perfect, thank you. This is the best practice lesson I needed.

    – phauwn
    Jan 2 at 21:43



















0














You should follow best practices like include nested records using includes that will avoid N+1 query problem.



If you want to do it anyway then try following:



  finance_experience_sum    += person.try(:finance_experience).try(:value).to_i #or to_f if float value
management_experience_sum += person.try(:manangement_experience).try(:value).to_i
clerical_experience_sum += person.try(:clerical_experience).try(:value).to_i


If you are using ruby 2.4 or later then use:



  finance_experience_sum    += person&.finance_experience&.value&.to_i
management_experience_sum += person&.manangement_experience&.value&.to_i
clerical_experience_sum += person&.clerical_experience&.value&.to_i





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53992638%2fsum-in-each-loop-when-object-might-be-nil%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    You can do simply like these without using the each loop



    finance_experience_sum = People.includes(:finance_experience).sum(:value)
    management_experience_sum = People.includes(:manangement_experience).sum(:value)
    clerical_experience_sum = People.includes(:clerical_experience).sum(:value)


    Always used ruby on rails best practices and predefined methods of ruby.






    share|improve this answer



















    • 1





      upvoted for reliable answer but need @people in place of People

      – ray
      Jan 2 at 11:07











    • need change in your profile link(experience section) for ajaydhande.github.io for carrier (need to be career)

      – ray
      Jan 2 at 11:09











    • Okay thanks for your suggestions

      – Cryptex Technologies
      Jan 2 at 11:11











    • @ray i will do that

      – Cryptex Technologies
      Jan 2 at 11:11











    • Perfect, thank you. This is the best practice lesson I needed.

      – phauwn
      Jan 2 at 21:43
















    2














    You can do simply like these without using the each loop



    finance_experience_sum = People.includes(:finance_experience).sum(:value)
    management_experience_sum = People.includes(:manangement_experience).sum(:value)
    clerical_experience_sum = People.includes(:clerical_experience).sum(:value)


    Always used ruby on rails best practices and predefined methods of ruby.






    share|improve this answer



















    • 1





      upvoted for reliable answer but need @people in place of People

      – ray
      Jan 2 at 11:07











    • need change in your profile link(experience section) for ajaydhande.github.io for carrier (need to be career)

      – ray
      Jan 2 at 11:09











    • Okay thanks for your suggestions

      – Cryptex Technologies
      Jan 2 at 11:11











    • @ray i will do that

      – Cryptex Technologies
      Jan 2 at 11:11











    • Perfect, thank you. This is the best practice lesson I needed.

      – phauwn
      Jan 2 at 21:43














    2












    2








    2







    You can do simply like these without using the each loop



    finance_experience_sum = People.includes(:finance_experience).sum(:value)
    management_experience_sum = People.includes(:manangement_experience).sum(:value)
    clerical_experience_sum = People.includes(:clerical_experience).sum(:value)


    Always used ruby on rails best practices and predefined methods of ruby.






    share|improve this answer













    You can do simply like these without using the each loop



    finance_experience_sum = People.includes(:finance_experience).sum(:value)
    management_experience_sum = People.includes(:manangement_experience).sum(:value)
    clerical_experience_sum = People.includes(:clerical_experience).sum(:value)


    Always used ruby on rails best practices and predefined methods of ruby.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jan 1 at 5:24









    Cryptex TechnologiesCryptex Technologies

    800213




    800213








    • 1





      upvoted for reliable answer but need @people in place of People

      – ray
      Jan 2 at 11:07











    • need change in your profile link(experience section) for ajaydhande.github.io for carrier (need to be career)

      – ray
      Jan 2 at 11:09











    • Okay thanks for your suggestions

      – Cryptex Technologies
      Jan 2 at 11:11











    • @ray i will do that

      – Cryptex Technologies
      Jan 2 at 11:11











    • Perfect, thank you. This is the best practice lesson I needed.

      – phauwn
      Jan 2 at 21:43














    • 1





      upvoted for reliable answer but need @people in place of People

      – ray
      Jan 2 at 11:07











    • need change in your profile link(experience section) for ajaydhande.github.io for carrier (need to be career)

      – ray
      Jan 2 at 11:09











    • Okay thanks for your suggestions

      – Cryptex Technologies
      Jan 2 at 11:11











    • @ray i will do that

      – Cryptex Technologies
      Jan 2 at 11:11











    • Perfect, thank you. This is the best practice lesson I needed.

      – phauwn
      Jan 2 at 21:43








    1




    1





    upvoted for reliable answer but need @people in place of People

    – ray
    Jan 2 at 11:07





    upvoted for reliable answer but need @people in place of People

    – ray
    Jan 2 at 11:07













    need change in your profile link(experience section) for ajaydhande.github.io for carrier (need to be career)

    – ray
    Jan 2 at 11:09





    need change in your profile link(experience section) for ajaydhande.github.io for carrier (need to be career)

    – ray
    Jan 2 at 11:09













    Okay thanks for your suggestions

    – Cryptex Technologies
    Jan 2 at 11:11





    Okay thanks for your suggestions

    – Cryptex Technologies
    Jan 2 at 11:11













    @ray i will do that

    – Cryptex Technologies
    Jan 2 at 11:11





    @ray i will do that

    – Cryptex Technologies
    Jan 2 at 11:11













    Perfect, thank you. This is the best practice lesson I needed.

    – phauwn
    Jan 2 at 21:43





    Perfect, thank you. This is the best practice lesson I needed.

    – phauwn
    Jan 2 at 21:43













    0














    You should follow best practices like include nested records using includes that will avoid N+1 query problem.



    If you want to do it anyway then try following:



      finance_experience_sum    += person.try(:finance_experience).try(:value).to_i #or to_f if float value
    management_experience_sum += person.try(:manangement_experience).try(:value).to_i
    clerical_experience_sum += person.try(:clerical_experience).try(:value).to_i


    If you are using ruby 2.4 or later then use:



      finance_experience_sum    += person&.finance_experience&.value&.to_i
    management_experience_sum += person&.manangement_experience&.value&.to_i
    clerical_experience_sum += person&.clerical_experience&.value&.to_i





    share|improve this answer




























      0














      You should follow best practices like include nested records using includes that will avoid N+1 query problem.



      If you want to do it anyway then try following:



        finance_experience_sum    += person.try(:finance_experience).try(:value).to_i #or to_f if float value
      management_experience_sum += person.try(:manangement_experience).try(:value).to_i
      clerical_experience_sum += person.try(:clerical_experience).try(:value).to_i


      If you are using ruby 2.4 or later then use:



        finance_experience_sum    += person&.finance_experience&.value&.to_i
      management_experience_sum += person&.manangement_experience&.value&.to_i
      clerical_experience_sum += person&.clerical_experience&.value&.to_i





      share|improve this answer


























        0












        0








        0







        You should follow best practices like include nested records using includes that will avoid N+1 query problem.



        If you want to do it anyway then try following:



          finance_experience_sum    += person.try(:finance_experience).try(:value).to_i #or to_f if float value
        management_experience_sum += person.try(:manangement_experience).try(:value).to_i
        clerical_experience_sum += person.try(:clerical_experience).try(:value).to_i


        If you are using ruby 2.4 or later then use:



          finance_experience_sum    += person&.finance_experience&.value&.to_i
        management_experience_sum += person&.manangement_experience&.value&.to_i
        clerical_experience_sum += person&.clerical_experience&.value&.to_i





        share|improve this answer













        You should follow best practices like include nested records using includes that will avoid N+1 query problem.



        If you want to do it anyway then try following:



          finance_experience_sum    += person.try(:finance_experience).try(:value).to_i #or to_f if float value
        management_experience_sum += person.try(:manangement_experience).try(:value).to_i
        clerical_experience_sum += person.try(:clerical_experience).try(:value).to_i


        If you are using ruby 2.4 or later then use:



          finance_experience_sum    += person&.finance_experience&.value&.to_i
        management_experience_sum += person&.manangement_experience&.value&.to_i
        clerical_experience_sum += person&.clerical_experience&.value&.to_i






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 1 at 10:11









        G.BG.B

        2,90821539




        2,90821539






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53992638%2fsum-in-each-loop-when-object-might-be-nil%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

            SQL update select statement

            'app-layout' is not a known element: how to share Component with different Modules