Rails 5、如何遍历活动记录集?

In Rails 5, how do I iterate over an active record set?

我正在使用 Rails 5. 我在迭代一组活动记录时遇到问题。我像这样访问它们

 priority_countries_ids = Country.where(:iso=>priority_countries).all
priority_countries_ids.each do |pc|

但是在 "each" 行,我得到了错误

can't quote Array

没有其他信息。我不知道如何解决这个问题,只是想遍历我的查询的每个结果。

你能打印 priority_countries 吗?你确定它是一个值数组吗? 尝试

Country.where(:iso=>priority_countries.to_a).all
priority_countries: [["US", "United States"], ["CA", "Canada"]]

问题是因为你的priority_countries不是一维数组。(http://edgeguides.rubyonrails.org/active_record_querying.html#retrieving-multiple-objects-in-batches)

priority_countries_ids = Country.where(:iso=>priority_countries.flatten).all // 使用展平将 priority_countries 转换为 1D。

希望它能解决您的问题。