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

有帮助吗?

解决方案

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.

其他提示

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top