views:

36

answers:

2

Hello,

I'm fairly new to Rails, and so I apologise if this is a daft question. I've tried looking around the web for the answer, but I'm not totally sure on the terminology and so I'm finding it really difficult to get an answer.

Basically, I have two models 'Group' and 'Category'. Groups has_one Categories, and Categories belongs_to Groups. What I'm trying to do, is get a list of Categories from a list of groups.

Something like this:

@groups = Group.find(:all)
@categories = @groups.<< insert magic code to get the categories >>

So I can do something like this in a view:

<% @categories.each do |cat| %>
<%= cat.title %> <% end %>

The problem is that I can't for the chickens of me figure out the magic code bit, or even exactly what I need to be searching for to learn how to do it.

Things I've tried:

@categories = @groups.categories @categories = @groups.category @categories = @groups.category.find(:all, :select => 'title') @categories = Category.find(:all, @groups.categories) @categories = Category.find(:all, @groups.categories.find(:all, :select => 'title'))

And various other takes on the above.

I'd really appreciate a solution and/or a pointer to where I could learn this for myself!

Thank you very much, SaoirseK

+2  A: 

I understand! It's hard to know what to search for when you don't know what it's called. This is easily done with pure Ruby, with the map instance method of the Array class:

categories = groups.map{|g| g.category}

A shorthand approach to this is:

categories = groups.map(&:category)

The map array method calls the given block for each element, and rolls all the return values into an array.

Jaime Bellmyer
Thank you very much, Jaime, that worked a treat!
SaoiseK
+1  A: 

I cannot think of some magic code to insert, but you can quite easily create the list without this magic code.

@categories = []
@groups.each do |group|
  @categories << @group.category unless @categories.include?(@group.category)
end

@categories now contains a list of all categories (each only included once).

Veger