0

Is it possible to parse an array of objects to select them by attribute? I have a situation where I need to display all objects of a model grouped by an attribute on the index page. What I had been doing in my controller is this...

#xx_controller.rb

@group1 = City.where(:population => 'big')
@group2 = City.where(:population => 'medium')
@group3 = City.where(:population => 'small')

But I'd prefer to do something like this in the controller...

@cities = City.all

And in my view something along the lines of a query, rather than prepackaged instance variables -

@cities.where....

Any thoughts?

2
  • I like the 1 database call way, but then I'd put them in groups in the controller. I'd rename the groups to something like @big_cities, @medium_cities, @small_cities also Commented Oct 4, 2012 at 0:41
  • So I found the answer elsewhere on stack... stackoverflow.com/questions/5269108/… :) Commented Oct 4, 2012 at 0:43

2 Answers 2

1

If you don't mind loading everything at once from the database, you can do:

@cities = City.all.group_by(&:population)

Which returns a hash whose keys are the possible values for the population attribute. Then, on your view, you can access the cities on each 'group' by doing @cities['small'], @cities['medium'] and so on.

Sign up to request clarification or add additional context in comments.

Comments

0

Do you mean something like this?

@cities = City.all

small_cities = @cities.select { |city| city.population == 'small' }
medium_cities = @cities.select { |city| city.population == 'medium' }
big_cities = @cities.select { | city| city.population == 'big' }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.