All threads / Searchkick search_data not working

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Searchkick search_data not working

Andrew Quinn asked in Gems / Libraries

I'm playing around with elasticsearch and searchkick, but I can't seem to get search_data working. Searchkick seems to ignore it all together.

If I only put one attribute in, it still searches on all the attributes. If I try and add a an attribute from a relation, it won't search on it. I've tried numerous syntaxes and now I'm at a total loss.

Here's my model:

class Contact < ActiveRecord::Base
    belongs_to :organization

    searchkick

    def search_data
        {
            fname: fname,
            lname: lname,
            cell_phone: cell_phone,
            work_phone: work_phone,
            organization_name: organization.name
        }
    end

end

I reindex after every change, but it doesn't seem to pick up changes to search_data. I've also tied numerous syntaxes for the relationship attribute including organization_name: organization(&:name).

Any help would be awesome.

Hey Andrew, did you get this one figured out?

Yes thank you, I got it sorted. Was just on vacation the last 2 weeks. Thanks for checkin in.

Was there any change to you code above? I'm having the same issue.

class Recipient < ActiveRecord::Base

  searchkick text_start: [:recipient_name]

  belongs_to :category

  def search_data
    {
      recipient_name: recipient_name,
      city: city,
      state: state,
      country: country,
      category_name: category.name
    }
  end
end

after running rake searchkick:reindex:all, I get the following error

Reindexing Recipient...
rake aborted!
NoMethodError: undefined method `name' for nil:NilClass
/Users/alexkale/Sites/dev/prnewswire/prn_product/app/models/recipient.rb:47:in `search_data'
Tasks: TOP => searchkick:reindex:all
(See full trace by running task with --trace)

Hey Alex,

That error is pointing out that it called .name on a class that was nil. The only line in your code that does this is category.name which means that you have a Recipient record without a category on it.

You probably want to conditionally pass in the category name if you want category to be optional.

            # using a ternary if statement
      category_name: category.present? ? category.name : nil

            # or, often not recommended to use try(), but a bit cleaner way of doing the above.
      #category_name: category.try(:name)
Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 34,885+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.