まずは通常のhas_many, belongs_toで繋がれた設定とembeds_manyの関係。
前提として、Storeにproductsが紐付いてること。
productを検索ボックスのparams[:q]で検索するという状況で説明する。
mongoidの場合、referenceにあるように、
to_indexed_jsonの中には、self.to_jsonで書くのが一般的。
readmeには以下のように書かれている。
で、このselfには、自動で、全てのfieldをindexes hogeで認識してくれる。
即ち、このproductにembeds_manyされているproduct_additionalsも
自動でincludeしてくれてる。とてもありがたい。
完璧にTireさんに甘やかされてます(∩´∀`)∩
class Productinclude Mongoid::Documentinclude Tire::Model::Searchinclude Tire::Model::Callbacksfield :product_name, type: Stringfield :product_description, type: Stringbelongs_to :storeembeds_many :product_additionals
def self.search(params)tire.search(load: true) doquery {string params[:q], default_operator: "AND"} if params[:q].present?endendtire.settings :analysis => {:analyzer => {:kuromoji => {"type" => "kuromoji","tokenizer" => "kuromoji_tokenizer"}}} dotire.mapping doindexes :description, :analyzer => :kuromojiindexes :product_name, :analyzer => :kuromoji, boost: 10indexes :store doindexes :branch_name, :analyzer => :kuromojiindexes :address, :analyzer => :kuromojiendendenddef to_indexed_jsonself.to_json(include: {store: {only: [:branch_name, :address]}})endend #ここからmodels/store.rbclass Storeinclude Mongoid::Documentinclude Mongoid::MultiParameterAttributeshas_many :products
field :branch_name #支店名field :address #住所end
productにとって厄介(has_manyなどの場合の込み入った設定)でないものは簡単にself.to_jsonの後ろにつけてincludeしてしまえばよい。
次回は、storeを検索した場合に、紐付いてるproductとproduct_additionalsをindexをはる方法を書きます。
今日はここまで。