2012-04-23 68 views
2

我有这个疑问语法错误:(IRB):26:给定两个块ARG和实际块

= 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)然后声明块来做错事。有没有一种方法可以完成两个相同的查询?

回答

6
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 ] }