Please see Gist: https://gist.github.com/KeweiCodes/dcb7508b65018fbd5696f487e6b6f47c
Hey @KeweiCodes, not sure I follow. Can you use the gist in the Contributing Guide to reproduce?
Hey @ankane , sorry for the late response, been very sick. Here's the gist: https://gist.github.com/KeweiCodes/dcb7508b65018fbd5696f487e6b6f47c
I also found that the searchkick call in the AR model file is stopping in-memory association, here're the experiments I did:
Without 'searchkick' : https://gist.github.com/KeweiCodes/16c92f752e25779a16ea853650039fa9
With 'searchkick' : https://gist.github.com/KeweiCodes/5370a59e4b3631a512e30c8205108385
First gist should print the 'supplier_connections' instance fine, but the second does not.
I know this may sound like a seperate problem but _my gut_ 漏 tells me they're related somehow.
Thanks @KeweiCodes. This is due to ActiveRecord caching, not Searchkick. If you print consumer.search_data right before consumer.reindex, you can see that there are no supplier connections.
Also, hope you're feeling better now.
Thanks @ankane for the quick response! I can understand that. Have you had a look at my other two gists? That behaviour is really strange...
If you add ActiveRecord logging, it's easier to see what's going on:
ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT)
When Searchkick is added to the model, the supplier_connections association is first called when the consumer is created. At this point, supplier_connections are empty, and ActiveRecord caches it.
When Searchkick is not present in the model, the supplier_connections association is not called until after the connection is created. At this point, supplier_connections is not empty.
Essentially, the fact that supplier_connections is referenced in the search_data method causes it be cached earlier in the example with Searchkick. You can get the same behavior if you manually call consumer.search_data right after the consumer is created in example without Searchkick.
Wow ok, that makes so much sense. Thank you so much @ankane !
So in my case this workaround seems to do the job:
def search_data
supplier_connections_index = [] unless changed?
supplier_connections_index ||= supplier_connections.map do |connection|
{
id: connection.id,
supplier_id: connection.supplier_id,
consumer_id: connection.consumer_id
}
end
{
id: id,
name: name,
supplier_connections: supplier_connections_index
}
end
It still seems incredibly hacky though :/
I think a less hacky way would be to do:
supplier_connections_index = supplier_connections.reload.map do ...