Pavel
Pavel

Reputation: 4420

sort by association field in sunspot

In my app I am using Sunspot for a fulltext search. The problem is that I want to have sorting by association model field. In my case:

class Movie < ActiveRecord::Base
  attr_accessible :description, :genre, :name
  has_many :premieres
end

and my Premier model has:

belongs_to :movie

Searching by movie name is done by defining the method:

def movie_name
  movie.name
end

but when I try to do:

order_by :movie_name, :asc

It says:

No field configured for Premiere with name 'movie_name'

How do I make this sorting available?

Upvotes: 0

Views: 261

Answers (1)

Moustafa Samir
Moustafa Samir

Reputation: 2268

you can do it like this

searchable auto_index: true do
  text :movie_name do
    if self.movie.present?
      self.movie.name
    end
  end
end

then you can use

order_by :movie_name, :asc

Upvotes: 1

Related Questions