Tire : Eager loading associations from multiple models

460 views Asked by At

I am using elasticsearch for querying in my application. Lets say there are 2 models

Class Topic
   has_many :posts

and

Class Article
  has_many :comments 

I want to do a combined search on both these models and my query looks like:

Tire.search [Article, Topic], {:load => {:include => [:posts, :comments]}} do |search|
...
end

This is where I encounter a problem. I get the

Association named comments not found

error. I think this is because Topic model doesn't have the association comments and I think the same thing will happen for posts with the Article model.

Is there anyway to solve this problem? I was thinking maybe something like

:include => ['topic.posts', 'article.comments']

Please help me out.

1

There are 1 answers

1
platforms On BEST ANSWER

I just solved a similar issue, based on some guidance I found on this post. That answer says to try this:

 Tire.search [Article, Topic], {:load => { Article =>{ :include => :comments}, 
                                           Topic => { :include => :posts }
                                         } }  do |search|

In my case, I needed a to load nested associations, where I had a two-deep hierarchy that I wanted Tire to eagerly load. So I adapted that solution to my case:

Tire.search 'articles', {:load => { :include => [:contributors, 
                                                 :books => [:authors]] } } do

Hope this helps.