Rails 4 order by virtual attribute

activerecord, ruby, ruby-on-rails, ruby-on-rails-4

Solution

If you do not put the value in a column or express the logic in `search_result_value` in pure SQL, then you’ll have to load all Products into memory and then sort them in Ruby using `sort_by`:

Product.all.to_a.sort_by(&:search_result_value)

Problem

I have a `Product` model which has `name` and `description` columns in the database. I also have a `Product.search_results_for(query)`, where `query` is a string like `"Green Apple"`. I need to return an `ActiveRecord::Relation` of the results ordered by which is the best hit. Currently, I'm setting a `search_result_value` to each product. `search_result_value` IS NOT a column in the database, and I don't want it to be. So in essence, I have an `ActiveRecord::Relation` of `Products` that I need to order by `search_result_value` without changing it to an array, which is an instance variable that isn't stored in the database. How can I do this? Something like this: ``` Product.order(:search_result_value) ```

Original source