Rails 3.2.13 アプリに次の 2 つのモデルがあります。
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
にはlocations_controller.rb
、次の検索方法があります。
def search
@results = Kaminari.paginate_array(Location.find_by_keyword(params[:keyword])).page(params[:page]).per(30)
end
gemを使用してmongoid_search
、Organization モデルと Location モデルの両方のすべてのフィールドでキーワード (検索語) を探し、一致するすべての Organization を取得できます。
orgs = Organization.full_text_search(keyword)
しかし、私が望むのは、組織に属するすべての場所を検索結果から返すことです。これを行うことができた唯一の方法は、各組織を繰り返し処理し、その場所を配列にプッシュしてから、フラット化された配列を返すことでした。コントローラーのコードを機能させるには、Kaminari のpaginate_array
方法を使用する必要がありました。
私の質問は、paginate_array
メソッドを使用せずに同じ結果を達成するためのより良い方法はありますか?
ありがとう!