Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 617
Martin Avatar asked Oct 23 '25 03:10

Martin


1 Answers

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 ] }
like image 177
Holger Just Avatar answered Oct 24 '25 20:10

Holger Just