Skip to main content
Ask A Question
Notifications
You’re not receiving notifications from this thread.
Subscribe

Searchkick search_data not working

Gems / Libraries • Asked by Andrew Quinn

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)

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,005+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.