How to restrict Sunspot search with nested models?

独自空忆成欢 提交于 2020-01-15 06:34:29

问题


I want to filter the Sunspot search results with with(:is_available, true). This is working with the User model, but I can't make it work with the Itinerary model.

app/controllers/search_controller.rb:

class SearchController < ApplicationController
  before_filter :fulltext_actions
  private
    def fulltext_actions
      @itineraries = do_fulltext_search(Itinerary)
      @users = do_fulltext_search(User)
      @itineraries_size = @itineraries.size
      @users_size = @users.size
    end
    def do_fulltext_search(model)
      Sunspot.search(model) do
        with(:is_available, true)
        fulltext params[:search]
      end.results
    end
end

app/models/user.rb:

class User < ActiveRecord::Base
  has_many :itineraries, :dependent => :destroy
  searchable do
    text :first_name, :boost => 3
    text :last_name, :boost => 3
    text :status
    boolean :is_available, :using => :available?
  end
  def available?
    !self.suspended
  end
end

app/models/itinerary.rb:

class Itinerary < ActiveRecord::Base
  belongs_to :user
  searchable do
    text :title, :boost => 3
    text :budget
    text :description
    boolean :is_available, :using => :available?
  end
  def available?
    !self.user.suspended
  end
end

Any ideas?

Thanks!


回答1:


Well, my real problem was the indexation.

When I update the User model, I set a flag (like user_instance.update_index_flag = true) in my controller.

In the User model:

attr_accessor :update_index_flag
after_save :reindex_sunspot
def reindex_sunspot
  if self.update_index_flag
    Sunspot.index(self.itineraries.to_a)
  end
end

That's it...



来源:https://stackoverflow.com/questions/8574173/how-to-restrict-sunspot-search-with-nested-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!