Search code examples
ruby-on-railscollection-select

Sort rails collection_select dropdown field by foreign attribute


I've got a collection_select and I want to sort it. usually no problem, just pass a collection.order(name DESC) or whatever to do that into the collection_select's collection field.

Unfortunately, my sort criteria is a foreign attribute, something like that: (saying we've got a posts and an author model, and I want to sort the posts by the authors name)

f.collection_select(:post, :post_id, Posts.order(author.name DESC), :id, :post_with_author_name_as_prefix)

...which of course does not work.

(post_with_author_name_as_prefix, the text method, would be a virtual method inside the posts model returning something like "John Doe: Random thoughts", which actually is the reason for that sort criteria...)

Any thougts how to get around that without big joins, db views and stuff like that?


Solution

  • Assuming a Post belongs to an Author, you can do this:

    Post.joins(:author).order("authors.name DESC")
    

    You should probably give it a name and make it part of the Post model:

    class Post < ActiveRecord::Base
      belongs_to :author
      scope :ordered_by_author, -> { joins(:author).order("authors.name DESC") }
      ...
    end
    

    And use in the view:

    <%= f.collection_select :post_id, Post.ordered_by_author, :id, :post_with_author_name_as_prefix %>