My Thread model has many Posts. Let’s say I want to reorder posts by an array containg ids I wish to see my posts sorted by.
thread.posts.collect {|x| x.id} # => [1,2,3]
order = [2,3,1]
posts = thread.posts.sort_by {|x| order.index x.id}
posts.collect {|x| x.id} # => [2,3,1]
thread.update_attributes(:posts => posts) # => true
thread.posts.collect {|x| x.id} # => [1,2,3]
What am I doing wrong? Is sorting by id always preserved in collections and can I somehow disable it?
You should always assume the order of results retrieved from your database as being more or less “random”, unless you specifically ask it to sort them. This means that you can not rely on your database to magically store the order of posts associated with a thread (in fact, the code sample you posted would probably not query the database at all, because there is nothing to update).
The easiest way to achieve what you want is to add an
orderfield to yourPostmodel like this:In your
Threadmodel:Afterwards you will be able to reorder the posts like this:
If you want, you can also use a plugin like
acts_as_listwhich provides this and other useful functionality.