Order by array

I need the id's order by a array.

def pages
    @admin = Admin.find(1)
    Page.find(:all, :order => [ @admin.sidebar ])

when the array has
2, 1, 3, 4, 5
the output is 2, 3, 4, 5, 1
and not the same as the array.
How can i order the output the same as the array?

i guess you could use the array to iterate through the collection (i'm
assuming that @admin.sidebar is an array)
<%= @admin.sidebar.each do |i| %>
   <%= @pages[i].foo %>
<% end %>

maybe there's a neater way

You could use acts_as_list for this.

Or, assuming that the order is distinct for each Admin and @admin.sidebar contains a list of Page#id values, you could:

Page.find(:all).sort_by { |page| @admin.sidebar.index(page.id) }

You might also consider having a separate model (called “Sidebar” perhaps?) that is something like:

class Sidebar < ActiveRecord::Base

belongs_to :admin

has_many :pages, :order => :position

acts_as_list :scope => :admin_id


which allows you to do:

class Admin

has_one :sidebar

has_many :pages, :through => :sidebar



(Warning: This is straight from me head and may contain typos or other problems)


Rob Biedenharn http://agileconsultingllc.com


acts_as_list is a undefined method.
Also in the api i cant't find acts_of_list
Maybe it is not a method in rails 2.0 or something

I tried all the methods described her but i get no result

% for @pages in pages %>
33: <% @admin.sidebar.each do |i| %>
34: <%= @pages[i].foo %>
36: <% end %>
37: <% end %>

wih this method i got the error

can't convert String into Integer

How can i save a array into the database?

Ryan Bigg wrote:

Use acts_as_list, it's a plugin that can be installed via script/plugin
install acts_as_list. It's exactly what you want.

37: <% end %>

Ryan Bigg
Feel free to add me to MSN and/or GTalk as this email.

Thanks for that that plugin that brings me a step closer.
Now i got this error.

Mysql::Error: #42S02Table 'webdesign_development.sidebars' doesn't
exist: SELECT * FROM `sidebars` WHERE (sidebars.admin_id = 1) LIMIT 1

I never worked with acts_as_list so i don't know what i must set into
that table a able with only admin_id gives no response

It's looking for a table called 'sidebars' in your webdesign_development schema. I have to guess (because you haven't supplied any additional code) that you're trying my suggestion of a Sidebar model. You also have to create that table (with a database migration) and then get the values in there.

If you want us to be able to help you, give more context to your posts and include actual code. Also, you can certainly try searching Google for things, too. (Hint: googling for "acts_as_list" would have told you exactly what Ryan did.)


Rob Biedenharn http://agileconsultingllc.com