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.

Reply

Hey Andrew, did you get this one figured out?

Reply

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

Reply

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)
Reply

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)
Reply
Join the discussion

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

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

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

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.