简体   繁体   中英

Search in belongs_to association in RoR, ElasticSearch with Searchkick

I have two models:

class Venue < ActiveRecord::Base
  has_many :loyalty_cards
end

class LoyaltyCard < ActiveRecord::Base
  belongs_to :venue
  searchkick word_start: [:venue_name, :venue_name_from_relation]

  def search_data
    attributes.merge(
      venue_name_from_relation: self.venue(&:name)
    )
  end
end

LoyaltyCard has two fields:

venue_id: int #used for relation with venue if such venue exists
venue_name: string #or you can add venue name manually when creating loyalty card

I want to search both fields and tried the following tweak as suggested at Searchkick isses at GitHub (ie https://github.com/ankane/searchkick/issues/112 ): searchkick word_start: [:venue_name, :venue_name_from_relation]

  def search_data
    attributes.merge(
      venue_name_from_relation: self.venue(&:name)
    )
  end

It searches venue_name successfully, however does not in associated venue.

I also tried doing the following (and few other variations):

  def search_data
    {
      venue_name_from_relation: venue.map(&:name)
    }
  end

however it fails reindexing with nil class error.

Any ideas?

thanks, Roman

To get the venue name correctly since it is a belongs_to association not a has_many

def search_data
  attributes.merge(
    venue_name_from_relation: self.venue_name_from_relation
  )
end

def venue_name_from_relation
  self.venue.name
end

Then use this to search

fields = ["venue_name", "venue_name_from_relation"]
LoyaltyCard.search(query, fields: fields, load: false)

or boost one field over another using (boost venue_name over venue_name_from_relation )

fields = ["venue_name^2", "venue_name_from_relation"]
LoyaltyCard.search(query, fields: fields, load: false)

Do not to forget to reindex before searching. LoyaltyCard.reindex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM