简体   繁体   中英

Rails tire(elasticsearch) search through has_many association

I have 2 associations

belongs_to :author
has_many :favorites

I'm wondering why this example works:

tire.search(load: {include: [:author, :comments]}, page: params[:page], per_page: 8) do
  query { string params[:query], default_operator: "AND" } if params[:query].present?
  filter :term, author_id: ['111']
  sort { by :created_at, 'desc' }
end

And this one doesnt:

tire.search(load: {include: [:author, :comments]}, page: params[:page], per_page: 8) do
  query { string params[:query], default_operator: "AND" } if params[:query].present?
  filter :term, favorite_ids: ['567']
  sort { by :created_at, 'desc' }
end

Can anyone help me?

Foreign keys are stored in the child table, Rails does the joining of the two tables for you.

So in this model, there is an attribute author_id because this model belongs to an author. The foreign keys for the favorites relationship are stored in the favorites table. While you can do Model.first.favorites and get the corresponding favorites , it is because of a value stored in the latter table.

Model.first.author_id exists. Model.first.favorite_ids does not.

If you want to run a search on favorites_ids , you're going to need to explicitly define that in the to_indexed_json method.

Also, tire has been retired. You should look into migrating to elasticsearch-rails , or my preferred gem, searchkick !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM