[英]Rails 3 - NoMethodError: undefined method for nil:NilClass in each Iteration
I'm iterating over an array of instances of a Rails model. 我正在遍历Rails模型的一系列实例。 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. “ product_detail”中的“标签”属性不是我的Rails ActiveRecord模型中的属性。 I added it with attr_accessor in my class definition. 我在类定义中添加了attr_accessor。 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. 当我在Rails控制台中运行没有“每个”迭代的代码时,它就可以正常工作。 But when I execute the above code I get the following error message: 但是当我执行上面的代码时,我收到以下错误消息:
NoMethodError: undefined method 'label' for nil:NilClass NoMethodError:nil:NilClass的未定义方法'label'
Did I do something obviously wrong? 我做错了什么吗? Many thanks in advance. 提前谢谢了。
You likely have several product_detail
items that have no matching product_group
. 您可能有几个没有匹配的product_group
product_detail
项。 So calling .first
on the empty collection returns nil
. 因此,在空集合上调用.first
返回nil
。 To get around the error, you can test if the product_group was found before proceeding: 要解决该错误,您可以在继续之前测试是否找到了product_group:
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. 这将导致单个数据库调用来获取所有相关组,并将标签放在键控哈希中,以便于发现和分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.