简体   繁体   中英

Rails 3 - NoMethodError: undefined method for nil:NilClass in each Iteration

I'm iterating over an array of instances of a Rails model. Here is my code:

product_details.each do |product_detail|
  product_detail.label = Backend::ProductGroup.where(product_group_number: product_detail.product_group).first.label

end

The attribute 'label' from 'product_detail' isn't an attribute from my Rails ActiveRecord model. I added it with attr_accessor in my class definition. I did this, because I wanted to add this attribute dynamically, only when I need to do this. When I ran the code without the 'each' iteration in my rails console it works just fine. But when I execute the above code I get the following error message:

NoMethodError: undefined method 'label' for nil:NilClass

Did I do something obviously wrong? Many thanks in advance.

You likely have several product_detail items that have no matching product_group . So calling .first on the empty collection returns nil . To get around the error, you can test if the product_group was found before proceeding:

product_details.each do |product_detail|
  product_group = Backend::ProductGroup.where(product_group_number: product_detail.product_group).first
  product_detail.label = product_group.label if product_group
end

You can also do this more efficiently like so:

group_labels = BackEnd::ProductGroup.
                 where(product_group_number: product_details.map(&:product_group)).
                 inject({}){|m, g| m[g.product_group_number] = g.label; m}
product_details.each do |product_detail|
  product_detail.label = group_labels[product_detail.product_group]
end

This will result in a single database call to grab all related groups, and put the labels in a keyed hash for easy discovery and assignment.

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