1
我有以下2種型號在Rails應用程序3.2.13文件:Mongoid:找到所有的孩子多個父文件
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
使用寶石,我可以在組織和位置模型的所有字段中查找關鍵字(搜索詞),並獲得所有匹配的組織:
orgs = Organization.full_text_search(keyword)
但我想要的是從搜索結果中返回屬於組織的所有位置。我能夠做到這一點的唯一方法是遍歷每個組織,然後將其位置推送到一個數組,然後返回扁平數組。爲了使控制器代碼正常工作,我必須使用Kaminari的paginate_array
方法。
我的問題是,有沒有更好的方法來實現相同的結果,而不使用paginate_array
方法?
謝謝!
謝謝!這更簡潔。 – monfresh