Question

I have the following 2 models in a Rails 3.2.13 app:

class Organization
  include Mongoid::Document
  include Mongoid::Search

  field :name
  field :description

  has_many :locations

  search_in :name, :description, :locations => [:name, :description, :keywords]
end

class Location
  include Mongoid::Document

  field :name
  field :description
  field :keywords, type: Array

  belongs_to :organization

  def self.find_by_keyword(keyword)
    locs = []
    orgs = Organization.full_text_search(keyword)
    orgs.each { |org| locs.push(org.locations) }
    locs.flatten
  end
end

In locations_controller.rb, I have this search method:

def search
  @results = Kaminari.paginate_array(Location.find_by_keyword(params[:keyword])).page(params[:page]).per(30)
end

Using the mongoid_search gem, I can look for the keyword (the search term) in all the fields for both the Organization and Location models, and get all Organizations that match:

orgs = Organization.full_text_search(keyword)

But what I want is to return all the locations that belong to the organizations from the search result. The only way I was able to do this was to iterate through each organization, then push its locations to an array, then return the flattened array. In order for the controller code to work, I had to use Kaminari's paginate_array method.

My question is, is there a better way to achieve the same result without using the paginate_array method?

Thanks!

Was it helpful?

Solution

You can use organization_id.in

@locations = Location.where(:organization_id.in => orgs.map(&:id))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top