Frage

I have an array of objects and every object respond to the 'order' method.

I can write the method

objects = Objects.all
objects.each do |i|
 puts i.order
end

but I'm not sure the order is correct. Is there any fast way to iterate my array following the right order of every object?

Update: real case.

class Articles < ActiveRecord::Base
 as_many :article_pages
end

a = Article.find(2345)
pages = a.article_pages
pages.each ...
pages.first.order = 1
pages.last.order = 5

I need to iterate in my pages following order...

a.article_pages.order('order').each

doesn't work

War es hilfreich?

Lösung

By default, ActiveRecord will not guarantee any order. To change that, use:

a = Article.find(2345)
pages = a.article_pages.order('order asc')

to order by a column. Switch asc to desc to order in descending order.

Andere Tipps

You can use sort option in case you want it in ascending only

a = Article.find(2345)
pages = a.article_pages.all.sort_by &:order
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top