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

旧城冷巷雨未停 提交于 2019-12-14 03:52:57

问题


I have this query

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

Problem is I'm getting the following error

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

From what I see I'm doing something wrong by including the collect(&:cities) and then declaring the block. Is there a way I can accomplish both with same query?


回答1:


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

is exactly the same as

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

And this is why you are getting your error: you pass two blocks to the collect method. What you actually meant was probably something like this:

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

That will retrieve the countries, get the list of cities for each country, flattens the array to that you only have a one-dimensional one and the returns your array for the select.

As there is probably only one country per country code, you can also write it that way:

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


来源:https://stackoverflow.com/questions/10288180/syntaxerror-irb26-both-block-arg-and-actual-block-given

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!