语法错误: (irb):26:给定的块参数和实际块



我有这个查询

= f.select(:city, Country.where(:country_code => "es").collect(&:cities) {|p| [ p.city, p.id ] }, {:include_blank => 'Choose your city'})

问题是我收到以下错误

SyntaxError: (irb):26: both block arg and actual block given

从我所看到的情况来看,我通过包含collect(&:cities)然后声明块而做错了什么。有没有办法用同一个查询来完成这两个问题?

Country.where(:country_code => "es").collect(&:cities)

Country.where(:country_code => "es").collect {|country| country.cities}

这就是你得到错误的原因:你把两个块传递给collect方法。你实际的意思可能是这样的:

Country.where(:country_code => "es").collect(&:cities).flatten.collect {|p| [ p.city, p.id ] }

这将检索国家/地区,获取每个国家/地区的城市列表,将数组展平到您只有一个一维数组,并返回您的数组以供选择。

由于每个国家/地区代码可能只有一个国家/地区,因此您也可以这样写:

Country.where(:country_code => "es").first.cities.collect {|p| [ p.city, p.id ] }

最新更新