Thursday, January 28, 2010

Tips - Thinking Sphinx Sort By Collection's Size

class Article < ActiveRecord::Base
  has_many :comments
  belongs_to :author
  # ...

  # ...
end
class Article < ActiveRecord::Base
  belongs_to :article
  # ...

  # ...
end
class Author < ActiveRecord::Base
  has_many :articles
  # ...
  
  define_index do
    indexes name, :sortable => true # search author's name
    
    # sort by articles.size that belongs to author
    has articles(:id)
    has "COUNT(articles.id)", :as => :articles_size, :type => :integer

    # sort by comments.size that belongs to article which belongs to author
    has articles.comments(:id)
    has "COUNT(articles.comments.id)", :as => :comments_size, :type => :integer
  end
  
  # ...
end
class AuthorsController < ApplicationController
  # ...

  @authors = Author.search "foo", :order => :articles_size
  
  @authors2 = Author.search "bar", :order => :comments_size


  # ...
end

No comments:

Post a Comment

© Railsmine