SyntaxError:(irb):26:既给出块arg又给出实际块

Mar*_*tin 3 ruby activerecord ruby-on-rails ruby-on-rails-3

我有这个问题

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

问题是我收到以下错误

SyntaxError: (irb):26: both block arg and actual block given
Run Code Online (Sandbox Code Playgroud)

从我看到我做错了包括collect(&:cities)然后声明块.有没有办法可以用同样的查询完成两个?

Hol*_*ust 8

Country.where(:country_code => "es").collect(&:cities)
Run Code Online (Sandbox Code Playgroud)

与...完全相同

Country.where(:country_code => "es").collect {|country| country.cities}
Run Code Online (Sandbox Code Playgroud)

这就是您收到错误的原因:您将两个块传递给collect方法.你真正的意思可能是这样的:

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

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

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

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