Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I search through associations with searchkick (elastic search) together aggregations

Owen asked in Rails

Hello folks,
I’m trying to do a search query through an association. Here’s what I have.
I have Property model which has_many :characteristics, as: characteristicable on one side. On the other side I have Characteristic model which belongs_to :characteristicable, polymorphic true .
I use Elastic Search in my rails app with the searchkick gem. What I’m trying to achieve is to search for characteristics in the Property model so that I can show all the properties that have that characteristic.
I’ve been playing around inside rails c and go something, but not quite what I’m looking for yet:

characteristic = Characteristic.find_by name: "Airconditioning"
# this finds the first instance with name "Airconditioning" in the Characteristics table
characteristic.characteristicable
# this gets the property that is linked to this instance of characteristic
characteristic = Characteristic.joins(:characteristicable).where name: "Airconditioning"
=> #<Characteristic::ActiveRecord_Relation:0x4d94>
#<Characteristic:0x00007fd694a789e8
  id: 20,
  name: "Airconditioning",
  description: nil,
  created_at: Sun, 21 Mar 2021 20:48:01.046319000 UTC +00:00,
  updated_at: Sun, 21 Mar 2021 20:48:01.046319000 UTC +00:00,
  characteristicable_type: "Property",
  characteristicable_id: 4,
  user_id: 1>,
[48] pry(main)> characteristic = Characteristic.joins(:characteristicable).where characteristicable_type: "Property"
=> #<Characteristic::ActiveRecord_Relation:0x4da8>
[49] pry(main)> characteristic
=> #<Characteristic::ActiveRecord_Relation:0x4da8>
[50] pry(main)> characteristic.find_by name: "Airconditioning"
ActiveRecord::EagerLoadPolymorphicError: Cannot eagerly load the polymorphic association :characteristicable
from /Users/owenmoss/.rbenv/versions/2.7.2/lib/ruby/gems/2.7.0/gems/activerecord-
Reply
Join the discussion
Create an account Log in

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

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

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