简体   繁体   中英

Why do I get 'undefined method `>=' for nil:NilClass' in do loop?

I have the following data architecture:

  :tplangroups has_many :tplans

  :tplans belongs_to :tplangroups

  :tplans has attr_accessible :favrank

I need to get the id of the tplan with the highest favrank from each tplangroup, this routine below is how I'm trying to accomplish that:

    <% @tplangroups.each_with_index do |tplangroup, index| %>
        <% @highest_favrank = 0 %>
        <% @highest_id = tplangroup.tplans[0] %>
        <% tplangroup.tplans.each do |tplan| %>  
            <% if tplan.favrank >= @highest_favrank %>
                <% @highest_favrank = tplan.favrank %>
                <% @highest_id = tplan.id %>
            <% end %>
        <% end %>
     #does stuff with tplangroup
     <% end %>

However, I keep getting the following error:

    undefined method `>=' for nil:NilClass

Any ideas? I really have no idea why it's throwing this error. I know that all of the attributes/variables I am referencing have values, I have tested this. I am not sure where I'm going wrong, thanks in advance!

The error message is pretty obvious: Your tplan.favrank is nil, and Ruby can't compare nil using >= to @highest_favrank .

You should remove nils from that array before you try to display it, using compact , or you should figure out why you are getting a nil.

Unfortunately, we can't tell you because you didn't supply code that shows how the values are created, nor is there data we can try to recreate your structure.

Maybe your table has nil values? Maybe your code is not trapping every condition, allowing nils to leak in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM