Unique values


#1

<% for room in @rooms %>

<%= room.city %> <% end %>

consider the above code… Is there an easy way in rails to get only the
unique values, not the doubles? Since, for instance, Amsterdam (my city
of habitat) will be returned about a thousend times or so, I want to
make a list of cities that have rooms available.

I know how to code a function for this, I was just wondering about
peoples thoughts on this (Am an absolute beginner myself, though been
coding other languages for years)

Thanks in advance!

Danny


#2

Daniel Owen van Dommelen wrote:

<% for room in @rooms %>

<%= room.city %> <% end %>

consider the above code… Is there an easy way in rails to get only the
unique values, not the doubles? Since, for instance, Amsterdam (my city
of habitat) will be returned about a thousend times or so, I want to
make a list of cities that have rooms available.

I know how to code a function for this, I was just wondering about
peoples thoughts on this (Am an absolute beginner myself, though been
coding other languages for years)

Thanks in advance!

Danny

In your controller:

@unique_rooms = @room.uniq

In your view:

<% for room in @unique_rooms %>

<%= room.city %> <% end %>

#3

In your controller:

@unique_rooms = @room.uniq

In your view:

<% for room in @unique_rooms %>

<%= room.city %> <% end %>

Er, on second thought why not just:

<% for room in @rooms.uniq %>

<%= room.city %> <% end %>

#4

Drew O. wrote:

In your controller:

@unique_rooms = @room.uniq

In your view:

<% for room in @unique_rooms %>

<%= room.city %> <% end %>

Er, on second thought why not just:

<% for room in @rooms.uniq %>

<%= room.city %> <% end %>

Thanks Drew, I believe that was the exact thing I was looking for,
somehow I knew I would be this easy in ruby :wink:

l8rs


#5

(Of course, this begins to be a bad example as it doesn’t sound like
Room belongs_to :city anyway.)

actually I believe that within my system (at work that is) rooms indeed
doesn’t belong to city, BUT city belongs to rooms though… or to be
true to form, city has many rooms :slight_smile:

but thanks a lot anyway, in this beginners stage any info on any topic
is most welcome!

  • Danny

#6

On Jan 16, 2007, at 12:11 PM, Drew O. wrote:

<%= room.city %> <% end %>

<% for city in @rooms.map(&:city).uniq.sort %>

<%= city %> <% end %>

or even: http://rdoc.caboo.se/doc/classes/ActionView/Helpers/
FormOptionsHelper.html#M004193

<%= options_for_select(@rooms.map(&:city).uniq.sort) %>

If you needed the value to be the city_id rather than the city
(name), you could:

<%= options_for_select(@rooms.map { |r| [ r.city,
r.city_id ] }.uniq.sort) %>

(Of course, this begins to be a bad example as it doesn’t sound like
Room belongs_to :city anyway.)

-Rob

Rob B. http://agileconsultingllc.com
removed_email_address@domain.invalid
Skype: rob.biedenharn