Question

I have a project model in my rails 3.1 application and I want to use Solr to run a search on it.

I defined the search like this:

  searchable do
    text :nr, :boost => 5  # nr is integer
    text :name, :boost => 5
    text :description, :boost => 2
    text :client do
      client.name
    end
    text :tasks do 
      tasks.map(&:name)
    end
  end

The project-nr, in my model just called nr, type integer, is the most used reference for finding a project.

Now besides having a search form I still want my projects ordered by the nr when no search was performed, but this does not work - my project seem to be in totally random order. The code of my ProjectsController index action looks like this:

  def index
    @search = Project.search do
      fulltext params[:search]
      paginate :page => params[:page]
      order_by :nr, :desc
    end 

    @projects = @search.results

    #@projects = Project.active.visible.design.order("nr desc")
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @projects }
    end

But when I visit then myapp/projects I get a

Sunspot::UnrecognizedFieldError in ProjectsController#index

No field configured for Project with name 'nr'

error...

any ideas what I need to do to order by nr. ?

thanks

Was it helpful?

Solution

Okay, I solved it by turning the nr field to an integer in my searchable:

searchable do
  integer :nr
  text :name, :boost => 5
  text :description, :boost => 2
  text :client do
    client.name
  end
  text :tasks do 
    tasks.map(&:name)
  end
end

Now I was able to order it nicely but I couldn't perform a text search on the project_nr anymore. So I added a virtual attribute name_number to my Project model and instead searched on this field.

  def name_number
    "#{self.nr} - #{self.name[0..24]}"
  end

Now I have ordering and searching in place... If there are other / better ideas, keep em coming!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top