AnApprentice
AnApprentice

Reputation: 110950

How to use Active Record Associations with ElasticSearch?

I have the following models:

class Document < ActiveRecord::Base
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks

  belongs_to :user
  belongs_to :authentication


class Authentication < ActiveRecord::Base
  belongs_to :user
  has_many :documents

I can query elastic search in my controller as follows:

@documents = Document.search params[:q]

@documents is populated correctly but I can no longer user ActiveRecord associations like so:

@documents.first.authentications.name

I get the following errors:

undefined method `authentication' for #<Elasticsearch::Model::Response::Result:0x007fd07929f5a8>

How can I make this work or is there a better way to handle this need?

Upvotes: 1

Views: 229

Answers (1)

Praveen Dhawan
Praveen Dhawan

Reputation: 300

I think you have a typo there while calling @documents.first.authentications.name. Note that you have an association belongs_to :authentication.

Please try @documents.results or @documents.records before calling first. So try @documents.records.first.authentications.name.

Upvotes: 1

Related Questions