Have you met ruby-debug? I find it invaluable when some code is not
doing what you expect, you can break in at the appropriate point and
examine the variables. Have a look at the rails guide on debugging.
(I presume you have already worked through the getting started guide.
The ActiveRecord associations one is compulsory also.)
Strange, t should be a single advert_type by the time it gets into the
block. As I expect you saw from the sort_by docs each item to be
sorted is passed into the block and the result used as the thing to
sort by. Can you paste the line of code it is failing on, together
with the surrounding ones. Use copy/paste rather than re-typing in
case there is a typo in it that you have not seen.
Firstly it would be much better to do this in the controller, or even
better in a method of one of the models. Secondly sort_by does not
modify the array (@advert_types in this case) it just returns another
array, so you have to say @advert_types = @advert_types.sort_by ...
Neither of which explains why t is an array. Are you sure that
@advert_types is what you think it is, an array of AdvertTypes? Could
it be something else. I suggest maybe looking at the docs for
group_by and possibly call it something different. Go in with the
debugger and have a look where you make advert_types. You can do
things like p @advert_types[0] and see what is in it.
28:
29: <% @advert_types.each do |type, adverts| %>
This is a bit of a clue that @advert_types is not an array of
AdvertTypes. You may need to make the contents of the block in
sort_by a little more subtle.
Have you considered grouping on the position rather than the type,
then the key will be the position itself and I think you should be
able to do something like
@whatever_you_want_to_call_them_sorted = @adverts.group_by { |advert|
advert.advert_type.position }.sort
Since you are grouping on the position 'type' should be the position.
To get the advert type do adverts[0].advert_type.name, or do it in the
adverts.each loop.