The first thing we need to do is to tell Sphinx which fields are sortable. To do this, we'll add :sortable => true to the indexes in our entity model. So now the indexes look like this:
indexes firstname, :sortable => true
indexes lastname, :sortable => true
Now we'll need to rebuild the indexes. Make sure that you shut down the Sphinx server if it's running or things won't work right (I think there's actually a way to rebuild the indexes on the fly without shutting the server down, but I'll have to investigate that later). To rebuild the indexes, we open the cmd window and type
And then restart the server:
Now, we'll just need to tell our controller to sort the results. In the home_controller.rb, the search now looks like this:
@entities = Entity.search params[:search],
:page => params[:page],
:per_page => 10,
:order => "lastname ASC, firstname ASC"
You'll notice that in the :order, we've included the ASC for each field we want to index by. This is not normally necessary in a standard Rails .find command. However, Sphinx is a little quirky and requires this. If it's not there, Sphinx won't return any results. You can't imagine how long it took me to figure this out. Of course, if I'd read the thinking_sphinx instructions, I would have seen this and saved myself a lot of frustration. Stupid me!
Anyway, if we now reload our home page, we should see sorted results. Woot!
Next time, I'll be trying to figure out how to do some advanced searching with our simple search box.
See ya next post!