9

I want to sort / order it (desc or asc how i want it) by the database table column "plays" Im totally confused. Just found a solution for select but not collection_select?

some code of my view

<%= f.collection_select :player1, Player.all, :id, :name %>

dont know how to sort / order

there are also columns in the database table like "plays", "goals" ...

0

1 Answer 1

22

Just pass actually ordered collection to collection_select helper:

collection_select(:post, :author_id, Author.order('created_at DESC'), :id, :name_with_initial, :prompt => true)

So, in your source example it will look like this:

<%= f.collection_select :player1, Player.order('plays DESC'), :id, :name %>
Sign up to request clarification or add additional context in comments.

2 Comments

dont know what you mean, am a newbie. could you change the code to my view so it will work and where to add this code by you? tried Player.all.order('created_at DESC') in the view but didnt work?
This is the right idea, but calling all executes the SQL query (which is why you can't call order afterward). You can simply move .all to the end of the chain or remove it completely since it is implied. <%= f.collection_select :player1, Player.order('plays DESC'), :id, :name %>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.